The Pitfalls of Async Void: A Detailed Explanation
Async void methods have established themselves as a poor practice in coding. This article delves deeper into why exactly this is the case, referencing the well-known article "Avoiding Async Void."
Reasons for Avoiding Async Void
Additional Considerations
Async void is considered an anomaly in the realm of async/await languages. Most languages, including F#, Python, JavaScript, and TypeScript, do not support it. Its inclusion in C#/VB was primarily to accommodate asynchronous event handlers.
A Preferred Approach
In your example, if you adjust your code to utilize async void event handlers:
protected override async void OnLoad(EventArgs e) { if (CustomTask == null) await PrimeCustomTask(); } private async Task PrimeCustomTask() {...}
Then the drawbacks of async void will be limited to the event handler, making exception handling, composition, and testing more manageable.
The above is the detailed content of Why Should I Avoid Async Void Methods in C#?. For more information, please follow other related articles on the PHP Chinese website!