Home > Backend Development > C++ > Await Task.Run(): What's the Difference Between `await Task.Run(); return;` and `return Task.Run()`?

Await Task.Run(): What's the Difference Between `await Task.Run(); return;` and `return Task.Run()`?

DDD
Release: 2025-01-30 03:46:10
Original
298 people have browsed it

Await Task.Run(): What's the Difference Between `await Task.Run(); return;` and `return Task.Run()`?

asynchronous operation:

The subtle difference between and await Task.Run(); return; return Task.Run()

At first glance, these two code seem to be very similar:

1

2

3

4

5

async Task TestAsync()

{

    await Task.Run(() => DoSomeWork());

    return;

}

Copy after login

1

2

3

4

Task TestAsync()

{

    return Task.Run(() => DoSomeWork());

}

Copy after login
Although both use

call asynchronous tasks, there are subtle and important differences in their behavior. Task.Run()

abnormal communication

The main difference is abnormal treatment. In the first example, the use of

and

will be captured and thrown out when the asynchronous method is waiting for the asynchronous method later. This allows the caller to handle abnormalities elegantly. await DoSomeWork() On the contrary, in the second example of

, any exception will spread immediately, and the execution of the call method may be interrupted. This may lead to unexpected behaviors and make abnormal treatment challenging.

await Synchronous above

Another difference is related to the synchronous context. In the Example, the operation in runs in the synchronous context of the calling thread. Instead, in the example, operates in the context of different thread pools.

Dead lock await DoSomeWork() return Task.Run() When performing asynchronous operations in the GUI application with non -default synchronization context, the

method is more likely to occur. For example, if you start asynchronous operations and use

from the UI thread, a deadlock may occur. Summary

await The results of these two code fragments are different, mainly because they are different from the use of abnormalities and the use of await. For asynchronous operations, the use of can better control abnormal dissemination and ensure that it is correctly implemented in the correct synchronization context.

The above is the detailed content of Await Task.Run(): What's the Difference Between `await Task.Run(); return;` and `return Task.Run()`?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template