Where does an async Task throw Exception if it is not awaited?

后端 未结 3 2220
天涯浪人
天涯浪人 2021-02-19 13:06

I have the following example: (please also read comments in code, as it will make more sense )

public async Task> MyAsyncMethod() 
{
           


        
3条回答
  •  旧巷少年郎
    2021-02-19 14:12

    I use an extension method for generic error handling on Task. This provides a way to both log all errors and do a custom action if an error occurs.

    public static async void ErrorHandle(this Task task, Action action = null)
    {
        try
        {
            await task.ConfigureAwait(false);
        }
        catch (Exception e)
        {
            Log.Error(e);
            if (action != null)
                action();
        }
    }
    

    I tend to use it when I do a "fire and forget" Task:

    Task.Run(() => ProcessData(token), token).ErrorHandle(OnError);
    

提交回复
热议问题