从Parallel.ForEach抛出时未处理的OperationCanceledException

时间:2012-09-24 00:08:38

标签: c# wpf exception-handling parallel.foreach

我正在尝试取消Parallel.ForEach循环。根据{{​​3}},这是可能的,我正在遵循他们的编码。

// Tokens for cancellation 
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;

try
{
    Parallel.ForEach(queries, po, (currentQuery) =>
    {
        // Execute query
        ExecuteQuery(currentQuery);

        // Throw exception if cancelled 
        po.CancellationToken.ThrowIfCancellationRequested(); // ***
    }); 
}
catch (OperationCanceledException cancelException)
{
    Console.WriteLine(cancelException.Message);
}

但是,当我从用户可访问的函数调用cts.Cancel();时,应用程序会在上面标有星号的行上崩溃并显示错误:

System.OperationCanceledException was unhandled by user code
  Message=The operation was canceled.
  Source=mscorlib
  StackTrace:
   at System.Threading.CancellationToken.ThrowIfCancellationRequested()
   at CraigslistReader.SearchObject.<>c__DisplayClass7.<bw_DoWork>b__5(Query currentQuery) in {PATH}:line 286
   at System.Threading.Tasks.Parallel.<>c__DisplayClass2d`2.<ForEachWorker>b__23(Int32 i)
   at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
InnerException: 

我有异常处理程序,所以我不明白崩溃。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

问题是po.CancellationToken.ThrowIfCancellationRequested();明确抛出了一个未处理的异常。异常处理程序可能在Parrallel.ForEach()调用周围,但异常不在lambda表达式中处理。删除行或在lambda表达式中添加异常处理程序,它应该工作。

有关详细信息,请参阅Cancelling a Task is throwing an exception