Asynchronous incident processing procedure: handle asynchronous space method
In the field of asynchronous programming, the practice of using the "Forgot to Forgot" to start the task is often not encouraged, because this method lacks traceability of hanging tasks, and it is difficult to deal with such methods. Abnormal. However, the question of the processing procedure of asynchronous events appears: Should we adopt the same principles of avoidance?
Reasons for the processing procedure of asynchronous events
There is no doubt that the recommended method is to avoid using asynchronous space. However, asynchronous space processing procedures are an exception. This is because event processing procedures have a natural asynchronous context, which are usually used for specific, disposable execution, so the lack of return value is not a problem.
Example: Re -examine the window loading scene
Considering the following asynchronous space incident processing procedures:
In order to reduce the potential defects, we can carry out the following reconstruction:
<code>private async void Form_Load(object sender, System.EventArgs e) { await Task.Delay(2000); // 执行异步操作 // ... } </code>
The hidden risk that needs attention
<code>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>
In addition to the potential re -incoming problem, there are still some more subtle risks in the processing procedures for asynchronous events:
Thread security:
The processing procedure of asynchronous events is essentially called on the UI thread. If the relevant asynchronous operation requires a long -term operation thread, it may cause the UI to respond without response.Odoma:
The above is the detailed content of Should Async Void Event Handlers Be Avoided?. For more information, please follow other related articles on the PHP Chinese website!