我正在使用 TPL 和 async/await 在 Webclient 之上为我的应用程序构建异步 API。很少有地方(通常是我需要运行一堆异步任务并最终等待所有任务的地方)遵循代码片段。我只是想确保我得到它的正确性,即使使用 TPL 和 async/await 编写异步代码相对容易调试/故障排除仍然具有挑战性(交互式调试和客户现场故障排除问题) - 所以希望得到正确的结果。
My Goal:能够捕获原始任务、延续任务以及子任务生成的异常,以便我可以处理它(如果需要)。我不希望任何例外被忽视和遗忘。
我使用的基本原则:1. .net框架确保异常将附加到任务
2. Try/catch 块可以应用于 async/await 以提供同步代码的错觉/可读性(参考:http://channel9.msdn.com/Events/TechDays/Techdays-2014-the-Netherlands/Async-programming-deep-dive http://channel9.msdn.com/Events/TechDays/Techdays-2014-the-Netherlands/Async-programming-deep-dive, http://blogs.msdn.com/b/ericlippert/archive/2010/11/19/asynchrony-in-c-5-part-seven-exceptions.aspx http://blogs.msdn.com/b/ericlippert/archive/2010/11/19/asynchrony-in-c-5-part-seven-exceptions.aspx, http://msdn.microsoft.com/en-us/library/dd537614.aspx http://msdn.microsoft.com/en-us/library/dd537614.aspx etc.)
Question:我希望得到批准,表明预期目标(我可以捕获原始任务、延续任务和子任务中的异常)已经实现,并且我可以对示例进行任何改进:
例如,是否会出现其中一个组合任务(例如,未包装的代理任务)根本不会被激活(waitforactivation 状态)的情况,因此 waitall 可能只是等待任务启动?我的理解是,这些情况永远不会发生,因为延续任务始终执行,并返回已使用 wnwrap 代理跟踪的任务。只要我在所有层和 API 中遵循类似的模式,该模式就应该捕获链式任务中的所有聚合异常。
Note:本质上是在寻找建议,例如如果原始任务状态未运行到完成,则避免在继续任务中创建虚拟任务,或者使用附加到父级,以便我只能等待父级等查看所有可能性,以便我可以选择最好的选项,因为此模式严重依赖我的应用程序进行错误处理。
static void SyncAPIMethod(string[] args)
{
try
{
List<Task> composedTasks = new List<Task>();
//the underlying async method follow the same pattern
//either they chain the async tasks or, uses async/await
//wherever possible as its easy to read and write the code
var task = FooAsync();
composedTasks.Add(task);
var taskContinuation = task.ContinueWith(t =>
{
//Intentionally not using TaskContinuationOptions, so that the
//continuation task always runs - so that i can capture exception
//in case something is wrong in the continuation
List<Task> childTasks = new List<Task>();
if (t.Status == TaskStatus.RanToCompletion)
{
for (int i = 1; i <= 5; i++)
{
var childTask = FooAsync();
childTasks.Add(childTask);
}
}
//in case of faulted, it just returns dummy task whose status is set to
//'RanToCompletion'
Task wa = Task.WhenAll(childTasks);
return wa;
});
composedTasks.Add(taskContinuation);
//the unwrapped task should capture the 'aggregated' exception from childtasks
var unwrappedProxyTask = taskContinuation.Unwrap();
composedTasks.Add(unwrappedProxyTask);
//waiting on all tasks, so the exception will be thrown if any of the tasks fail
Task.WaitAll(composedTasks.ToArray());
}
catch (AggregateException ag)
{
foreach(Exception ex in ag.Flatten().InnerExceptions)
{
Console.WriteLine(ex);
//handle it
}
}
}