0

我有一个应用程序从 Listbox 中获取所有添加的文件并播放此文件。

这是IEnumerable<string> source通过另一个类获取和播放文件的类:

public CancellationTokenSource _tokenSource { get; set; }
private IEnumerable<string> _source;

    public void play(PacketDevice selectedOutputDevice, double speed, int parallelThreads)
    {
        var token = _tokenSource.Token;
        if (token.IsCancellationRequested)
        {
            return;
        }

        Task.Factory.StartNew(() =>
        {
            try
            {
                Parallel.ForEach(_source,
                    new ParallelOptions
                    {
                        MaxDegreeOfParallelism = 1;
                    },
                    file =>
                    {
                        processFile(file, selectedOutputDevice, speed, parallelThreads);
                        //token.ThrowIfCancellationRequested();
                    });
            }
            catch (AggregateException)
            {

            }

        }, _tokenSource.Token).ContinueWith(
                t =>
                {
                    OnFinishPlayEvent();
                }
            , TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
            );
    }

从停止按钮单击事件下的主窗体中,我正在更改_tokenSource.Cancel();,但我的问题是我的循环继续工作并且没有停止。

4

1 回答 1

1

您需要在以下范围内手动处理取消请求Parallel.ForEach

var token = _tokenSource.Token;

Parallel.ForEach(_source,
    new ParallelOptions
    {
        MaxDegreeOfParallelism = 1//limit number of parallel threads 
    },
    file =>
    {
        //here i am process my file via another class

        // Cancel if required
        token.ThrowIfCancellationRequested();
    });

话虽这么说,如果你要设置MaxDegreeOfParallelism = 1,没有理由使用Parallel.ForEach,因为它会有效地按顺序运行。

于 2013-06-03T18:43:14.527 回答