"Fire and forget" in C#: Async/Await vs. old async delegates - which approach is best?
In an attempt to simplify "fire and forget" calls in C#, developers may encounter challenges when transitioning to the new asynchronous syntax. This article explores the differences between the old ways and the new ways.
In the old approach (demonstrated by the "async" delegate in the sample code), the underlying thread was terminated once the EndInvoke() method was called. The BeginInvoke() method ensures that the thread is started, allowing "start and forget" operations to call the DoIt() method asynchronously. While this approach works, it requires manually closing the async wait handle.
New asynchronous syntax (exemplified by the DoIt2() method) eliminates the need for EndInvoke() and handle closing. However, it introduces the requirement to await Task.Yield(), which requires existing async methods to be overridden to add this placeholder.
To solve the problem of calling synchronous method A() asynchronously without creating unnecessary complexity, developers can avoid using async void and call A() directly using Task.Run(A). This approach emulates the old async delegate without the complexity of async/await.
The above is the detailed content of Fire-and-Forget in C#: Async/Await vs. the Old Async Delegate – Which Approach Is Best?. For more information, please follow other related articles on the PHP Chinese website!