In gen­eral, when you see async void in your code it’s bad news, because:

  1. you can’t wait for its com­ple­tion (as men­tioned in this post already)
  2. any unhan­dled excep­tions will ter­mi­nate your process (ouch!)

 

Sup­pose you have a timer event that fires every once in a while and you want to do some asyn­chro­nous pro­cess­ing inside the han­dler, so you pro­ceed to write some­thing along the lines of:

The fact that your timer event excepted might hurt, that it took your whole process with it is likely to hurt an awful lot more!

Well, what are your options? If you change the han­dler to return Task instead the code won’t com­pile because ElapsedE­ven­tHandler del­e­gate type spec­i­fies a void return type. Annoyed

Two options springs to mind here.

First, you can always just exe­cute the whole block of code syn­chro­nously instead.

This is not ideal because it’s going to block the thread whilst it’s wait­ing for the asyn­chro­nous oper­a­tion to come back, pre­vent­ing the thread from being used to do other use­ful work in the mean time.

If you wish to per­sist with using async-await and just wish to swal­low any excep­tions then you can con­sider option two:

In this case, we’ve sim­ply used a con­tin­u­a­tion (which fires regarded whether the pre­ced­ing task had faulted) to swal­low any excep­tion that had been thrown by the asyn­chro­nous operations.

 

Hope this helps, and remem­ber, when­ever you see async void in your code it should be trig­ger­ing off your spi­der senses!

Share

One Response to “C# – beware of async void in your code”

  1. […] 2. the pro­posed solu­tion still wouldn’t work with async meth­ods that return void sim­ply because there are no returned Task/Task<T> objects to hook up con­tin­u­a­tions with. In gen­eral though, you should avoid hav­ing async void meth­ods as much as pos­si­ble because they intro­duce some pit­falls which you really wouldn’t want to find your­self in! I’ve dis­cussed the prob­lem with aysnc void (and some poten­tial workarounds) in a pre­vi­ous post here. […]

Leave a Reply