async/await - when to return a Task vs void?

后端 未结 7 1168
梦如初夏
梦如初夏 2020-11-21 23:47

Under what scenarios would one want to use

public async Task AsyncMethod(int num)

instead of

public async void AsyncMetho         


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 00:13

    I got clear idea from this statements.

    1. Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext(SynchronizationContext represents a location "where" code might be executed. ) that was active when the async void method started

    Exceptions from an Async Void Method Can’t Be Caught with Catch

    private async void ThrowExceptionAsync()
    {
      throw new InvalidOperationException();
    }
    public void AsyncVoidExceptions_CannotBeCaughtByCatch()
    {
      try
      {
        ThrowExceptionAsync();
      }
      catch (Exception)
      {
        // The exception is never caught here!
        throw;
      }
    }
    

    These exceptions can be observed using AppDomain.UnhandledException or a similar catch-all event for GUI/ASP.NET applications, but using those events for regular exception handling is a recipe for unmaintainability(it crashes the application).

    1. Async void methods have different composing semantics. Async methods returning Task or Task can be easily composed using await, Task.WhenAny, Task.WhenAll and so on. Async methods returning void don’t provide an easy way to notify the calling code that they’ve completed. It’s easy to start several async void methods, but it’s not easy to determine when they’ve finished. Async void methods will notify their SynchronizationContext when they start and finish, but a custom SynchronizationContext is a complex solution for regular application code.

    2. Async Void method useful when using synchronous event handler because they raise their exceptions directly on the SynchronizationContext, which is similar to how synchronous event handlers behave

    For more details check this link https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

提交回复
热议问题