[英]Is the below code captures the exceptions from original, continuation and child tasks in TPL?
我正在使用 TPL 和 async/await 在 webclient 之上为我的应用程序构建异步 API。 很少有地方(通常我需要运行一堆异步任务并在最后等待所有任务的地方)遵循代码片段。 我只是想确保我得到它的正确性,因为即使使用 TPL 编写异步代码相对容易,并且异步/等待调试/故障排除仍然具有挑战性(客户站点的交互式调试和故障排除问题) - 所以想要做对.
我的目标:能够捕获从原始任务、延续任务以及子任务生成的异常,以便我可以处理它(如果需要)。 我不希望任何例外被冷漠和遗忘。
我使用的基本原则: 1. .net 框架确保异常将附加到任务 2. Try/catch 块可以应用于 async/await 以提供同步代码的错觉/可读性(参考: http://channel9.msdn。 com/Events/TechDays/Techdays-2014-the-Netherlands/Async-programming-deep-dive , http://blogs.msdn.com/b/ericlippert/archive/2010/11/19/asyncchrony-in-c- 5-part-seven-exceptions.aspx , http://msdn.microsoft.com/en-us/library/dd537614.aspx等)
问题:我想获得批准,即我可以从原始任务、延续任务和子任务中捕获异常的预期目标已经实现,并且我可以对示例进行任何改进:
例如,是否会出现其中一个组合任务(例如,未包装的代理任务)根本不会被激活(waitforactivation 状态),从而使 waitall 可能只是等待任务开始的情况? 我的理解是这些情况不应该发生,因为继续任务总是执行,并返回一个使用 wnwrap 被代理跟踪的任务。 只要我在所有层和 api 中遵循类似的模式,该模式就应该捕获链式任务中的所有聚合异常。
注意:本质上是在寻找建议,例如如果原始任务状态未完成,则避免在继续任务中创建虚拟任务,或者使用附加到父级以便我只能等待父级等查看所有可能性,以便我可以选择最好的选择,因为这种模式严重依赖我的应用程序进行错误处理。
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
}
}
}
来自评论:
IMO,这段代码可以使用 async/await 更简单和优雅。 我不明白您坚持使用 ContinueWith 和 Unwrap 的原因,以及您将内部和外部(未包装的)任务都添加到composedTasks 的原因。
我的意思是像下面这样。 我认为它做同样的事情,你原来的代码,但没有的形式不必要的冗余composedTasks
, ContinueWith
和Unwrap
。 如果您使用async/await
您几乎不需要它们。
static void Main(string[] args)
{
Func<Task> doAsync = async () =>
{
await FooAsync().ConfigureAwait(false);
List<Task> childTasks = new List<Task>();
for (int i = 1; i <= 5; i++)
{
var childTask = FooAsync();
childTasks.Add(childTask);
}
await Task.WhenAll(childTasks);
};
try
{
doAsync().Wait();
}
catch (AggregateException ag)
{
foreach (Exception ex in ag.Flatten().InnerExceptions)
{
Console.WriteLine(ex);
//handle it
}
}
}
static async Task FooAsync()
{
// simulate some CPU-bound work
Thread.Sleep(1000);
// we could have avoided blocking like this:
// await Task.Run(() => Thread.Sleep(1000)).ConfigureAwait(false);
// introduce asynchrony
// FooAsync returns an incomplete Task to the caller here
await Task.Delay(1000).ConfigureAwait(false);
}
更新以解决评论:
在某些用例中,我在“创建子任务”之后继续调用更多“独立”任务。
基本上,任何异步任务工作流都有三种常见场景:顺序组合、并行组合或这两者的任意组合(混合组合):
顺序组合:
await task1; await task2; await task3;
平行组合:
await Task.WhenAll(task1, task2, task3); // or await Task.WhenAny(task1, task2, task3);
混合成分:
var func4 = new Func<Task>(async () => { await task2; await task3; }); await Task.WhenAll(task1, func4());
如果上述任何任务执行 CPU 密集型工作,您可以使用Task.Run
,例如:
var task1 = Task.Run(() => CalcPi(numOfPiDigits));
其中CalcPi
是一种进行实际计算的同步方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.