Home > Backend Development > C++ > Async Methods: Task.Run vs. Native Async - When Should I Use Which?

Async Methods: Task.Run vs. Native Async - When Should I Use Which?

Susan Sarandon
Release: 2025-01-03 17:05:40
Original
613 people have browsed it

Async Methods: Task.Run vs. Native Async - When Should I Use Which?

Async Methods: Task.Run vs. Native Async

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;
    });
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template