The subtle difference between and await Task.Run(); return;
return Task.Run()
1 2 3 4 5 |
|
1 2 3 4 |
|
call asynchronous tasks, there are subtle and important differences in their behavior. Task.Run()
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
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
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!