我试图理解为什么下面的代码:
async void Handle_Clicked(object sender, System.EventArgs e)
{
try
{
await CrashAsync("aaa");
}
catch (Exception exception)
{
Log($"observed exception");
Log($"Exception: {exception.Message}");
}
}
private async Task CrashAsync(string title)
{
Log($"CrashAsync ({title}) - before");
await Task.Delay(1000);
throw new Exception($"CrashAsync ({title})");
Log($"CrashAsync ({title}) - after");
}
产生预期的结果:
thread #1: CrashAsync (aaa) – before
thread #1: observed exception
thread #1: Exception: CrashAsync (aaa)
但如果我将其更改为此:
async void Handle_Clicked(object sender, System.EventArgs e)
{
try
{
await CrashAsync("aaa").ContinueWith(async (t) =>
{
await CrashAsync("bbb");
},TaskContinuationOptions.OnlyOnRanToCompletion);
}
catch (Exception exception)
{
Log($"observed exception");
Log($"Exception: {exception.Message}");
}
}
我得到以下输出:
thread #1: CrashAsync (aaa) – before
thread #1: observed exception
thread #1: Exception: A task was canceled.
thread #2: unobserved exception
thread #2: System.Exception: CrashAsync (aaa)
at AsyncTest.AsyncTestPage+c__async3.MoveNext () [0x000ad] in /Users/johndoe/Development/Xamarin/AsyncTest/AsyncTest/AsyncTestPage.xaml.cs:82
哪里:
TaskScheduler.UnobservedTaskException += (sender, e) =>
{
Debug.WriteLine($"thread #{Environment.CurrentManagedThreadId}: unobserved exception");
foreach (var exception in e.Exception.Flatten().InnerExceptions)
{
Debug.WriteLine($"thread #{Environment.CurrentManagedThreadId}: {exception}");
}
};
连续条件不满足,因此ContinueWith任务被取消,但是为什么我有未观察到的异常?
解决方法:
您等待由ContinueWith返回的Task,因此您观察到与该Task相关的异常-该异常已被取消(TaskCanceledException).但是,您不会观察到CrashAsync引发的原始异常(即“ CrashAsync aaa”)异常,因此不会观察到行为.
以下是示例代码,可以帮助您进一步理解:
static async void Test() {
var originalTask = CrashAsync("aaa");
var onSuccess = originalTask.ContinueWith(async (t) =>
{
await CrashAsync("bbb");
}, TaskContinuationOptions.OnlyOnRanToCompletion);
var onFault = originalTask.ContinueWith(t => {
Log("Observed original exception: " + t.Exception.InnerExceptions[0].Message);
}, TaskContinuationOptions.OnlyOnFaulted);
}
简而言之-等待您的任务并捕获异常(如果有).您根本不需要使用ContinueWith,因为如果您使用await,则该方法的其余部分已经是延续.