Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does c# handle async void

Tags:

c#

async-await

I generally program webservers and at first I thought that there must be continuous chain of methods that return task, so stuff up the stack may ask database if it is done.

Recently I saw wpf code, that does something like that:

    public async void Execute(object parameter)
    {
        await ExecuteAsync(parameter);
    }

Called in event handler. UI seems to be responsive, so I guess it does work. How does it work? How does this translate to aspnet?

like image 726
Shadow Avatar asked Dec 03 '22 23:12

Shadow


2 Answers

I explain how async void methods work - and why they should be avoided - in my Best Practices in Asynchronous Programming article.

async void has the same semantics as async Task, except for exceptions. An async void method will capture the current SynchronizationContext at the beginning of the method, and any exceptions from that method will be captured and raised directly on that captured context. In the most common scenarios, this will cause an application-level exception, usually a crash. Some people call async void methods "fire-and-forget", but because of their exceptional behavior, I prefer "fire-and-crash". :)

"Avoid async void" is the general guideline, with one notable exception: event handlers (or items that are logically event handlers, such as ICommand.Execute implementations).

How does it work? How does this translate to aspnet?

It works just like any other async method. The main platform difference is that the UI thread doesn't need to know when the async method completes. ASP.NET needs to know that so it knows when to send the request, but the UI has no need to know when the async method completes. So async void works. It's still best avoided, because the calling code usually does need to know when it completes.

like image 80
Stephen Cleary Avatar answered Dec 20 '22 20:12

Stephen Cleary


Async void is only to be used for event handler/delegate comparability. that Execute is a event callback, likely from a DelegateCommand or similar.

The way it works is it treats it exactly the same as if you had a function that returned a Task but the caller never called await on that returned task.

On ASP.NET you are likely to never use async void and instead be using controllers that expose methods that return a Task<ActionResult>, use HostingEnviorment.QueueBackgroundWorkItem, or using functions that are wrapped up in a Page.RegisterAsyncTask in situations where you would have used async void in normal desktop programming.

public void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(LoadSomeData));
}
like image 28
Scott Chamberlain Avatar answered Dec 20 '22 18:12

Scott Chamberlain