Asynchronous Event Handlers: A Deep Dive into Using async void
While it is generally accepted to avoid the "fire and forget" async void
approach, the question is: should asynchronous void
event handlers be avoided as well?
Consider the following code snippet:
<code class="language-csharp">private async void Form_Load(object sender, System.EventArgs e) { await Task.Delay(2000); // 执行异步操作 // ... }</code>
As an alternative, a more structured approach can be chosen:
<code class="language-csharp">Task onFormLoadTask = null; 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); // 执行异步操作 // ... }</code>
Apart from potential reentrancy issues, what are the hidden pitfalls of using asynchronous event handlers?
Surprisingly, general guidelines recommend using async void
in event handlers, which makes it an exception to the "don't use async void
" rule. This is because:
However, in some cases it may be more beneficial to break out the logic of an asynchronous event handler for the following reasons:
Example:
<code class="language-csharp">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); }</code>
By following these guidelines, you can use asynchronous event handlers effectively while mitigating potential risks and ensuring the maintainability of your code.
The above is the detailed content of Async Event Handlers: To Use `async void` or Not?. For more information, please follow other related articles on the PHP Chinese website!