一些伪代码来说明我的问题:
public async Task DoSomethingAsync()
{
try
{
var task1 = DoThisAsync(); // throws exception
var task2 = DoThatAsync();
await task1.Then(t => Handle(t));
await task2.Then(t => Handle(t));
}
catch (AggregateException)
{
Console.WriteLine("Whatnow?");
}
}
然后定义如下:
// from https://gist.github.com/rizal-almashoor/2818038
public static Task Then(this Task task, Action<Task> next)
{
var tcs = new TaskCompletionSource<AsyncVoid>();
task.ContinueWith(t=>
{
if (t.IsFaulted)
tcs.TrySetException(t.Exception); // continuing task1 this line only gets hit
// after DoThatAsync() is completed??
else
{
try
{
next(t);
tcs.TrySetResult(default(AsyncVoid));
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
});
return tcs.Task;
}
所以我的问题是,出于某种原因,即使 DoThisAsync() 很早就抛出了异常,但在 DoThatAsync() 完成之前我看不到“whatnow”。这不是确切的代码,我试图简化以免浪费您的时间。如果这里没有任何东西可以解释这种行为,请告诉我,我会添加更多细节。
编辑
出于这个问题的目的,我们可以想象 DoThisAsync() 和 DoThatAsync() 是异步方法,基本上执行以下操作:
DoThisAsync:
Thread.Sleep(30000); // wait a short perioud of time
throw new Exception(); // and throw an exception
DoThatAsnyc:
Thread.Sleep(240000); // wait a long period of time