简体   繁体   中英

What are the consequences of defining async task as event of a windows forms component?

It's a common sense we shouldn't use async void on normal methods around our codes, with some exceptions, like EventHandlers of winforms (or WPF) components:

public async void OnButtonClicked(object sender, EventArgs args)
{
    await DoSomethingAsync();
}

but what'd be the consequences of doing something like this?

button.OnClick += async (obj, e) => await AsyncTaskButtonClickEvent(obj ,e);

async Task AsyncTaskButtonClickEvent(object sender, EventArgs args) {  }
...

In your second example, you created a lambda that calls a method with the exact same signature, which doesn't make much sense. Perhaps you meant to make it like the following:

button.OnClick += async (obj, e) => await DoSomethingAsync();

Assuming you did, the only difference is you are comparing a method vs a lambda. I suggest reading C# Lambda expressions: Why should I use them? to understand the differences.

Using async void in event handlers is the only way to do it. That's pretty much why async void is allowed, so you can wire up event handlers to async methods. Using async Task will result in a compiler error, given that the event handler delegate signature is this:

public delegate void EventHandler(object sender, EventArgs e);

You should also take a look at these two articles as there are often problems with async event handlers, such as deadlocks:

Async/Await - Best Practices in Asynchronous Programming

https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

The two are equivalent BUT. The async void is a well known "hive for bugs". If you go async all the way, and encounter a problem with two threads accesing something at the same time, you might want to start debugging from regex search "async void". The first example, will guide you directly to the source. The second one not at all. I'd prefer the first one, because it bears a DANGER sign.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM