Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I avoid 'async void' event handlers?

People also ask

Why is it that using async functions with event handlers is problematic?

Using async functions with event handlers is problematic, because it can lead to an unhandled rejection in case of a thrown exception: const ee = new EventEmitter(); ee. on('something', async (value) => { throw new Error('kaboom'); });

Can event handlers be async?

The solution is extremely simple: just mark the event handler as async. You should never use async void methods, instead use async Task or async Task<T1,...>. The exception, apparently, is event handlers. And it kind of makes sense: an event handler is designed to be called asynchronously.

Is it OK to not await async?

You should consider suppressing the warning only if you're sure that you don't want to wait for the asynchronous call to complete and that the called method won't raise any exceptions. In that case, you can suppress the warning by assigning the task result of the call to a variable.


The guideline is to avoid async void except when used in an event handler, so using async void in an event handler is OK.

That said, for unit testing reasons I often like to factor out the logic of all async void methods. E.g.,

public async Task OnFormLoadAsync(object sender, EventArgs e)
{
  await Task.Delay(2000);
  ...
}

private async void Form_Load(object sender, EventArgs e)
{
  await OnFormLoadAsync(sender, e);
}

Should I generally avoid async void event handlers, as well?

Generally event handlers are the one case where a void async method is not a potential code smell.

Now, if you do need to track the task for some reason then the technique you describe is perfectly reasonable.


Yes, generally async void of event handlers is the only case. If you want to know more about it you can check out a great video here at channel 9

The only case where this kind of fire-and-forget is appropriate is in top-level event-handlers. Every other async method in your code should return "async Task".

here is the link


If you use ReSharper, a free ReCommended Extension could be helpful for you. It analyzes the "async void" methods and highlights when used inappropriately. The extension can distinguish different usages of async void and provide appropriated quick fixes described here: ReCommended-Extension wiki.