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

后端 未结 7 1160
梦如初夏
梦如初夏 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-21 23:51

    I have come across this very useful article about async and void written by Jérôme Laban: https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html

    The bottom line is that an async+void can crash the system and usually should be used only on the UI side event handlers.

    The reason behind this is the Synchronization Context used by the AsyncVoidMethodBuilder, being none in this example. When there is no ambient Synchronization Context, any exception that is unhandled by the body of an async void method is rethrown on the ThreadPool. While there is seemingly no other logical place where that kind of unhandled exception could be thrown, the unfortunate effect is that the process is being terminated, because unhandled exceptions on the ThreadPool effectively terminate the process since .NET 2.0. You may intercept all unhandled exception using the AppDomain.UnhandledException event, but there is no way to recover the process from this event.

    When writing UI event handlers, async void methods are somehow painless because exceptions are treated the same way found in non-async methods; they are thrown on the Dispatcher. There is a possibility to recover from such exceptions, with is more than correct for most cases. Outside of UI event handlers however, async void methods are somehow dangerous to use and may not that easy to find.

提交回复
热议问题