C# – beware of async void in your code

In gen­er­al, 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 except­ed might hurt, that it took your whole process with it is like­ly 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­nous­ly instead.

This is not ide­al 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 oth­er 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­sid­er option two:

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


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