我试图允许取消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);
}
但是,当我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:
我在那里有异常处理程序,所以我不明白崩溃。有任何想法吗?