Home >Backend Development >C++ >How Can I Call Asynchronous Methods from Synchronous Methods in C#?
Calling asynchronous methods in synchronous code (usually async modification symbol logo) is a common development problem. Asynchronous programming can perform the operation of the CEO for a long time while maintaining the UI response, but this usually needs to adjust the code structure, which may not match the existing synchronization method.
Plan 1: task.waitandunwrapexception
If the asynchronous method (MyasyncmedHod) can run independently, without the need to synchronize the context, you can use task.waitandunwrapexception to provide a simple solution:
However, you need to pay attention when using task.wait or task.Result, they will pack abnormal packaging in AggregateException.
<code class="language-csharp">var task = MyAsyncMethod(); var result = task.WaitAndUnwrapException();</code>Plan 2: AsyncContext.runtask
or, if myAsyncmedhod needs to be synchronized with context, asynccontext.runtask provides a method of nested context:
Plan 3: task.run
<code class="language-csharp">var result = AsyncContext.RunTask(MyAsyncMethod).Result;</code>In some cases, asyncContext.runtask may be limited, such as asynchronous methods that depend on UI events. In this case, the asynchronous method can be performed on the thread pool:
Please note that this method requires that MyasyncmetHod can be compatible with the context of the thread pool, including the restrictions on UI element updates and ASP.NET request context access.
The above is the detailed content of How Can I Call Asynchronous Methods from Synchronous Methods in C#?. For more information, please follow other related articles on the PHP Chinese website!