wpf 从 Parallel.ForEach 抛出时未处理的 OperationCanceledException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12557371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unhandled OperationCanceledException when thrown from Parallel.ForEach
提问by Doug
I am trying to allow cancellation of a Parallel.ForEachloop. According to this MSDN article, it is possible, and I am following their coding.
我试图允许取消Parallel.ForEach循环。根据这篇 MSDN 文章,这是可能的,我正在关注他们的编码。
// 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);
}
However, when I call cts.Cancel();from a user-accessible function, the app crashes on the line marked with asterisks above with the error:
但是,当我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:
I have the Exception handler right there, so I don't understand the crash. Any ideas?
我在那里有异常处理程序,所以我不明白崩溃。有任何想法吗?
采纳答案by akton
The issue is that po.CancellationToken.ThrowIfCancellationRequested();is explicitly throwing an exception, which is unhandled. The exception handler may be around the Parrallel.ForEach()call but the exception is not handled within the lambda expression. Either remove the line or add an exception handler within the lambda expression and it should work.
问题是po.CancellationToken.ThrowIfCancellationRequested();显式抛出未处理的异常。异常处理程序可能在Parrallel.ForEach()调用周围,但不在 lambda 表达式中处理异常。删除该行或在 lambda 表达式中添加一个异常处理程序,它应该可以工作。
See Cancelling a Task is throwing an exceptionfor more information.
有关更多信息,请参阅取消任务引发异常。

