Home >Backend Development >C++ >Async Methods: Task.Run vs. Native Async - When Should I Use Which?
When working with asynchronous programming, it's crucial to understand the difference between executing code asynchronously and creating awaitable methods.
Task.Run and Asynchronous Execution:
Task.Run executes code on a background thread, making it appear asynchronous. However, this approach does not create a truly asynchronous method. The calling thread remains blocked until the Task completes.
Example:
private async Task DoWork2Async() { Task.Run(() => { int result = 1 + 2; }); }
In this example, DoWork2Async is not truly asynchronous since the calling thread will still be blocked while the Task executes on a background thread.
Native Async Methods:
Native async methods are declared with the async keyword and enable yielding of control back to the caller before execution begins. The caller can then continue executing other code while waiting for the async operations to complete.
Example:
private async Task DoWork1Async() { int result = 1 + 2; }
In this example, DoWork1Async is a native async method. When you await it, the calling thread will be released, allowing other code to execute while waiting for the asynchronous operation to be completed.
Conclusion:
To create an awaitable asynchronous method, the async keyword should be used without wrapping the synchronous code in Task.Run. This allows for true asynchronous execution, where the calling thread is not blocked while the async operation is being performed.
The above is the detailed content of Async Methods: Task.Run vs. Native Async - When Should I Use Which?. For more information, please follow other related articles on the PHP Chinese website!