停止我的任务和我所有的等待任务

时间:2013-06-03 15:44:52

标签: c# winforms

我有一个应用程序从我的Listbox获取所有添加的文件并播放这些文件:

IEnumerable<string> source

public void play()
{
    Task.Factory.StartNew(() =>
    {
        Parallel.ForEach(source,
                         new ParallelOptions
                         {
                             MaxDegreeOfParallelism = 1 //limit number of parallel threads 
                         },
                         file =>
                         {
                              //each file process via another class
                         });
    }).ContinueWith(
            t =>
            {
                OnFinishPlayEvent();
            }
        , TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
        );
    }

我的处理文件可以通过我的类属性停止,但如果我想停止所有文件 那等着我该怎么办?

2 个答案:

答案 0 :(得分:1)

您需要设计例程以接受CancellationToken,然后触发CancellationTokenSource.Cancel()

这将允许您提供合作取消工作的机制。

有关详细信息,请参阅MSDN上的Cancellation in Managed ThreadsTask Cancellation

答案 1 :(得分:0)

如果要停止并行循环,请使用ParallelLoopState类的实例。要取消任务,您需要使用CancellationToken。由于您将并行循环嵌入到任务中,因此您只需将取消令牌传递给任务即可。请记住,如果您选择等待任务,这将抛出您必须捕获的OperationCanceledException。

例如,为了论证,我们假设其他人会在你的类中调用一个将设置取消令牌的委托。

CancellationTokenSource _tokenSource = new CancellationTokenSource();

//Let's assume this is set as the delegate to some other event
//that requests cancellation of your task
void Cancel(object sender, EventArgs e)
{
  _tokenSource.Cancel();
}

void DoSomething()
{
  var task = Task.Factory.StartNew(() => { 
    // Your code here...
  }, _tokenSource.Token);

  try {
    task.Wait();
  }
  catch (OperationCanceledException) {
    //Carry on, logging that the task was canceled, if you like
  }
  catch (AggregateException ax) {
    //Your task will throw an AggregateException if an unhandled exception is thrown
    //from the worker. You will want to use this block to do whatever exception handling
    //you do.
  }
}

请记住,有更好的方法可以做到这一点(我在这里输入内存,因此可能会出现一些语法错误等),但这应该可以让你开始。