Home >Backend Development >C++ >Async/Await: Should I Wrap My Method in `Task.Run` for Background Threading?
In the pursuit of understanding async/await, the dilemma arises: Is it necessary to encapsulate a method within Task.Run to achieve both async behavior and background thread execution?
"Async" denotes a method that can yield control to the calling thread before commencing execution. This yielding occurs through await expressions. In contrast, "asynchronous" as defined by MSDN (an often misleading term) refers to code that runs on a separate thread.
Separately, "awaitable" describes a type that can be used with the await operator. Common awaitables include Task and Task
To execute a method on a background thread while maintaining awaitability, utilize Task.Run:
private Task<int> DoWorkAsync() { return Task.Run(() => 1 + 2); }
However, this approach is generally discouraged.
To create an async method that can pause and yield control, declare the method as async and employ await at designated yielding points:
private async Task<int> GetWebPageHtmlSizeAsync() { var html = await client.GetAsync("http://www.example.com/"); return html.Length; }
Async code relies on awaitables in its await expressions. Awaitables can be either other async methods or synchronous methods that return awaitables.
Avoid indiscriminately wrapping synchronous methods within Task.Run. Instead, maintain synchronous signatures, leaving the option of wrapping to the consumer.
The above is the detailed content of Async/Await: Should I Wrap My Method in `Task.Run` for Background Threading?. For more information, please follow other related articles on the PHP Chinese website!