

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 that was active when the async void method started. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. However, some semantics of an async void method are subtly different than the semantics of an async Task or async Task method.Īsync void methods have different error-handling semantics. Event handlers naturally return void, so async methods return void so that you can have an asynchronous event handler.

It is possible to have an event handler that returns some actual type, but that doesn't work well with the language invoking an event handler that returns a type is very awkward, and the notion of an event handler actually returning something doesn't make much sense. Void-returning async methods have a specific purpose: to make asynchronous event handlers possible. The following code snippet illustrates a synchronous void-returning method and its asynchronous equivalent: void MyMethod() When converting from synchronous to asynchronous code, any method returning a type T becomes an async method returning Task, and any method returning void becomes an async method returning Task. There are three possible return types for async methods: Task, Task and void, but the natural return types for async methods are just Task and Task. Prefer async Task methods over async void methods The guidelines are summarized in Figure 1 I’ll discuss each in the following sections.įigure 1 Summary of Asynchronous Programming Guidelines Name I’ll explain the reasoning behind each guideline so that it’s clear when it does and does not apply. There are exceptions to each of these guidelines. The best practices in this article are more what you’d call “guidelines” than actual rules. This article just highlights a few best practices that can get lost in the avalanche of available documentation. This article presents nothing new, as the same advice can be found online in sources such as Stack Overflow, MSDN forums and the async/await FAQ. This article is intended as a “second step” in learning asynchronous programming I assume that you’ve read at least one introductory article about it. These days there’s a wealth of information about the new async and await support in the Microsoft. Volume 28 Number 03 Async/Await - Best Practices in Asynchronous Programming
