Async and Await Demystified: Avoiding the Task.Run Conundrum
Understanding async and await can be tricky at first, but breaking down the concepts can simplify the process.
Async vs. Background Thread Execution
Async does not inherently mean "background thread"; it refers to methods that allow for "yielding" control to the calling thread before proceeding. These yield points are marked with await expressions.
Awaitable vs. Async
Awaitable types can be waited upon (as in await expressions), while async methods allow for asynchronous execution. Not all async methods return awaitable types, and vice versa.
Task.Run for Background Execution
If you want to execute an operation on a background thread and make it awaitable, use Task.Run:
private Task<int> DoWorkAsync() { return Task.Run(() => 1 + 2); }
Async Methods for Yielding
Create async methods that yield back to the caller by using await and async in the method signature:
private async Task<int> GetWebPageHtmlSizeAsync() { var client = new HttpClient(); var html = await client.GetAsync("http://www.example.com/"); return html.Length; }
Avoid Task.Run in Synchronous Methods
It's not recommended to wrap synchronous methods in Task.Run. If you need to execute on a background thread, create a separate task.
Resources for Further Exploration
The above is the detailed content of When Should I Use `Task.Run` with Async and Await?. For more information, please follow other related articles on the PHP Chinese website!