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.
var task = MyAsyncMethod(); var result = task.WaitAndUnwrapException();
or, if myAsyncmedhod needs to be synchronized with context, asynccontext.runtask provides a method of nested context:
<案> Plan 3: task.run
var result = AsyncContext.RunTask(MyAsyncMethod).Result;
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!