Should I avoid async void event handlers?

I know that it is usually a bad idea to use fire-and-forget async void methods to start tasks, because there is no way to a waiting task, and it is difficult to handle exceptions that can be thrown inside such a method.

Should I avoid async void event handlers at all? For example,

 private async void Form_Load(object sender, System.EventArgs e) { await Task.Delay(2000); // do async work // ... } 

I can rewrite it like this:

 Task onFormLoadTask = null; // track the task, can implement cancellation private void Form_Load(object sender, System.EventArgs e) { this.onFormLoadTask = OnFormLoadTaskAsync(sender, e); } private async Task OnFormLoadTaskAsync(object sender, System.EventArgs e) { await Task.Delay(2000); // do async work // ... } 

What are the pitfalls for asynchronous event handlers besides the possible re-entry?

+74
c # asynchronous events async-await
16 Oct '13 at 23:21
source share
4 answers

The recommendation is to avoid async void , except when used in the event handler, so using async void in the event handler is fine.

However, for unit testing reasons, I often like to classify the logic of all async void methods. For example.

 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); } 
+94
Oct. 16 '13 at 23:25
source share

Should I avoid async void event handlers at all?

In the general case, event handlers are the case when the aoid void method is not a potential code smell.

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

+35
Oct 16 '13 at 23:25
source share

Yes, usually async void event handlers are the only case. If you want to know more about this, you can watch a great video here on 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's the link

+4
Sep 07 '14 at 6:34
source share

If you use ReSharper, the free ReCommended Extension may be helpful. It analyzes the methods of "asynchronous voids" and selects them when used improperly. The extension can distinguish between different uses of async void and provide the quick fixes described here: ReCommended-Extension wiki .

+3
Jan 31 '16 at 0:34
source share



All Articles