取消我的任务并行循环

时间:2013-06-03 18:38:17

标签: c# winforms

我有一个应用程序从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();但我的问题是我的循环继续工作而不是停止。

1 个答案:

答案 0 :(得分: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,因为它会有效地按顺序运行。