Home >Backend Development >C++ >Await Task.Run() vs. Return Task.Run(): What are the Key Differences in C# Asynchronous Programming?
C#asynchronous programming
The key difference between await Task.Run()
return Task.Run()
In asynchronous programming, it is often necessary to perform operations outside the UI thread to avoid the application of the application. This can be achieved through the task in C#. However, there are subtle differences between
when dealing with abnormalities and other aspects. await Task.Run()
return Task.Run()
<.> 1. Disposure:
The main difference is that abnormal communication. In situation:
The abnormalities in the asynchronous task will only spread the callback method only when waiting for the task. await Task.Run()
return Task.Run()
This may lead to accidental errors and potential deadlocks.
On the contrary, the version does not depend on the context of synchronization. Continuing the arrangement of the default task scheduling program, which may be different from the synchronization context of calling threads.
<.> 3. The generated code: await Task.Run()
return Task.Run()
Code example:
The following code example illustrates these differences:
Example 1: await Task.Run()
return Task.Run()
In these two examples, "dosomework ()" is a method of performing certain jobs outside the UI thread.
Conclusion:
The choice of and
depends on the specific needs of the application. When controlling abnormal dissemination and ensuring correct synchronization context is important, it is recommended to use<code class="language-csharp">async Task TestAsync() { await Task.Run(() => DoSomeWork()); // 异常在等待时传播回 }</code>. When it is not a problem to spread anomalies or synchronize contexts immediately,
is suitable.
The above is the detailed content of Await Task.Run() vs. Return Task.Run(): What are the Key Differences in C# Asynchronous Programming?. For more information, please follow other related articles on the PHP Chinese website!