【发布时间】:2014-03-28 23:49:32
【问题描述】:
我想知道总体而言,哪种方法在内存和资源使用方面更有效。
特别是方法#1,我很难想象任务对象将如何创建和线程如何启动?有人可以详细解释一下幕后发生的事情吗?
如果两者之间没有区别,我想使用#1(希望避免冒泡异步)。使用#2,我知道编译器将在下面生成一个状态机并产生返回。 OTOH,#1 在概念上似乎是递归的,但在传统意义上它会像一个堆栈帧在另一个等待另一个堆栈帧那样是递归的吗?
方法一:
internal static Task ExecuteAsyncWithRetry(Func<Task> methodToExecute, Func<bool> shouldRetry)
{
var tcs = new TaskCompletionSource<object>();
try
{
return methodToExecute().ContinueWith<Task>((t) =>
{
if (t.IsFaulted || t.IsCanceled)
{
if (shouldRetry())
{
return ExecuteAsyncWithRetry(methodToExecute, shouldRetry);
}
else
{
tcs.SetException(t.Exception);
}
}
else
{
tcs.SetResult(null);
}
return tcs.Task;
}, TaskContinuationOptions.ExecuteSynchronously).Unwrap();
}
catch(Exception ex)
{
tcs.SetException(ex);
}
return tcs.Task;
}
方法#2(忽略两者在异常传播上的差异):
internal static async Task ExecuteWithRetry(Func<Task> methodToExecute, Func<bool> shouldRetry)
{
while (true)
{
try
{
await methodToExecute();
}
catch(Exception ex)
{
if(!shouldRetry())
{
throw;
}
}
}
}
【问题讨论】:
-
第二种方法更易于阅读和理解。我的经验法则:尽可能使用 async-await。在你的情况下,这是可能的。但是在第二种情况下,您缺少某种终止条件。如果一切顺利,
methodToExecute()将被一遍又一遍地执行。 -
注意,await 会丢失错误信息,因为它会解开 AggregateException 的包装。这对于像这样的通用辅助方法是不可取的。它不涉及解释异常。
-
谢谢,@usr,但是,你能澄清一下丢失错误信息部分吗? await 不应该表现得像 UnWrap() 并传播内部任务的错误/异常吗?
-
默认等待者丢弃除第一个内部异常之外的所有异常。
标签: c# asynchronous task-parallel-library async-await