Asynchronous programming is becoming more and more popular in C#development. Sometimes you may encounter the situation that needs to call asynchronous methods from the synchronization context. Although this is usually implemented by asynchronous methods, this article discusses various methods that brought to this gap.
Method 1: Use task.waitandunwrapexception
If your asynchronous method is simple and does not need to be synchronized with its context, you can use Task.waitandunwrapexception to retrieve its results. This method will solve any abnormalities that may occur during the asynchronous operation.
Method 2: Use asyncContext.runtask
<code class="language-csharp">var task = MyAsyncMethod(); var result = task.WaitAndUnwrapException();</code>
For the method that needs to be synchronized with context, you can use AsyncContext.runtask to create a nested context. By default, AsyncContext encapsulates the current synchronization context. However, it can be applied to any any context.
Method 3: Use task.run
<code class="language-csharp">var result = AsyncContext.RunTask(MyAsyncMethod).Result;</code>
Precautions
When using these methods, please remember the following points:
<code class="language-csharp">var task = Task.Run(async () => await MyAsyncMethod()); var result = task.WaitAndUnwrapException();</code>
Methods only applies to the method that does not require context synchronization.
Method 2 If the asynchronous method is waiting for the UI incident, it may lead to a deadlock.Method three requires that asynchronous methods are properly operated on multi -threaded context.
The above is the detailed content of How to Call Asynchronous Methods from Synchronous Code in C#?. For more information, please follow other related articles on the PHP Chinese website!