Home >Backend Development >C++ >Should You Avoid Async Void Event Handlers?
Event processing procedure: Should it be avoided?
async void
Generally speaking, the best practice suggestions to avoid using the method, especially when starting the task, because they lack the mechanism of tracking and hanging tasks, and the abnormal processing is more complicated. But is this principle applied to the
async void
Let's take a look at an example: async void
Instead of using this method, it is better to redesign the code to achieve task tracking and canceling function:
<code class="language-csharp">private async void Form_Load(object sender, System.EventArgs e) { await Task.Delay(2000); // 执行异步操作 // ... }</code>
In addition to the potential re -incoming problem, what are the hidden traps in the
incident processing procedure?<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>
The key is that the use of async void
is persuaded in the context that cannot be elegant to handle abnormalities. However, in the event processing procedure, abnormalities will be processed by routing to global abnormal processing to ensure that they are appropriately captured and processed without explicit error treatment in the event processing program itself. This is the key difference between in this specific situation.
In order to test the unit, the usual approach is to extract all the logic of all async void
methods for isolation: async void
In short, although the async void
method is usually not recommended, they are acceptable to use them in the
<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>in the event processing program without violating the best practice.
The above is the detailed content of Should You Avoid Async Void Event Handlers?. For more information, please follow other related articles on the PHP Chinese website!