Gra*_* H. 0 c# exception task-parallel-library parallel.foreach
如果在控制台应用程序中运行而不是将其抛出AggregateException并被外部捕获,以下的崩溃为什么会崩溃try/catch?
I've simplified the use case for the await for brevity, but in the relevant code I am indeed trying to execute an awaitable Task of importance.
var list = new List<string>() {"Error"};
try
{
Parallel.ForEach(list, new ParallelOptions()
{
MaxDegreeOfParallelism = 8
}, async listEntry =>
{
await Task.Delay(5000);
throw new Exception("Exception");
});
}
catch (Exception ex)
{
//never hits, the application crashes
}
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
I note that the following does not cause the application to fail, and an exception is indeed caught, but I do not understand what's really going on as to what is fundamentally different about the two contexts:
var list = new List<string>() {"Error"};
try
{
Parallel.ForEach(list, new ParallelOptions()
{
MaxDegreeOfParallelism = 8
}, listEntry =>
{
throw new Exception("Exception");
});
}
catch (Exception ex)
{
//exception is caught, application continues
}
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
正如评论中已经提到的,您不应该混合使用async和Parallel.ForEach,它们不能一起使用。
您所观察到的是其中的后果之一:lambda作为async void方法被编译,并且当async void方法抛出时,异常将重新抛出,SynchronizationContext通常会导致应用程序崩溃。
| 归档时间: |
|
| 查看次数: |
1051 次 |
| 最近记录: |