C# async / await unobserved exception

前端 未结 1 1116
情话喂你
情话喂你 2021-01-20 18:05

I\'m trying to understand why the following code:

async void Handle_Clicked(object sender, System.EventArgs e)
{
    try
    {
        await CrashAsync(\"aaa         


        
1条回答
  •  走了就别回头了
    2021-01-20 18:52

    You await Task returned by ContinueWith, so you observe exception related to this Task - that it was cancelled (TaskCanceledException). But you don't observe original exception thrown by CrashAsync (so "CrashAsync aaa") exception, hence the behavior you observe.

    Here is sample code to get more understanding:

    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);
    }
    

    So in short - just await your task and catch exception if any. You don't need to use ContinueWith at all, because if you use await - the rest of the method is already a continuation.

    0 讨论(0)
提交回复
热议问题