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

后端 未结 3 2182
天涯浪人
天涯浪人 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 13:49

    This is a lot of questions to pack into a single "question", but OK...

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

    Unobserved Task exceptions are raised by the TaskScheduler.UnobservedTaskException event. This event is raised "eventually" because the Task must actually be garbage collected before its exception is considered unhandled.

    As I don't await for the actual Result in the MyAsyncMethod and if PostAsync method throws an exception, in which context is the exception going to be thrown and handled?

    Any method that uses the async modifier and returns a Task will put all of its exceptions on that returned Task.

    Is there any way I can handle exceptions in my assembly?

    Yes, you could replace the returned task, something like:

    async Task HandleExceptionsAsync(Task original)
    {
      try
      {
        return await original;
      }
      catch ...
    }
    
    public async Task> MyAsyncMethod()
    {
      Task resultTask = await _mySender.PostAsync();
      return HandleExceptionsAsync(resultTask);
    }
    

    I was surprised that when I tried to change MyAsyncMethod to [synchronously return the inner task] the exception was caught here, even if there's no await for the actual result.

    That actually means that the method you're calling is not async Task, as your code example shows. It's a non-async, Task-returning method, and when one of those methods throws an exception, it's treated just like any other exception (i.e., it passes directly up the call stack; it's not placed on the returned Task).

    Is it possible to use ContinueWith to handle exceptions in the current class?

    Yes, but await is cleaner.

提交回复
热议问题