Task<T>
) to improve the performance and response capacity of the application. However, in some cases, you may need to perform asynchronous methods synchronously to debug or test. Task<T>
method, which will block the calling thread until the task is completed. However, in some cases, this will cause UI freezing and performance problems. Task.Wait()
method. Although it sounds to run the task simultaneously, if the task is not bound to the commission, it will actually throw an exception. Task.RunSynchronously()
attribute of the scheduling program to DispatcherFrame
to stop the scheduling program pump. Continue
false
A reliable solution
How to use:
public static class AsyncHelpers { /// <summary> /// 同步执行具有 void 返回值的异步 Task 方法。 /// </summary> /// <param name="task">要执行的 Task 方法。</param> public static void RunSync(Func<Task> task) { var oldContext = SynchronizationContext.Current; var syncContext = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(syncContext); syncContext.Post(async _ => { try { await task(); } catch (Exception e) { syncContext.InnerException = e; throw; } finally { syncContext.EndMessageLoop(); } }, null); syncContext.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); } /// <summary> /// 同步执行具有 T 返回类型的异步 Task<T> 方法。 /// </summary> /// <typeparam name="T">返回类型</typeparam> /// <param name="task">要执行的 Task<T> 方法。</param> /// <returns>等待给定的 Task<T> 的结果。</returns> public static T RunSync<T>(Func<Task<T>> task) { var oldContext = SynchronizationContext.Current; var syncContext = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(syncContext); T result; syncContext.Post(async _ => { try { result = await task(); } catch (Exception e) { syncContext.InnerException = e; throw; } finally { syncContext.EndMessageLoop(); } }, null); syncContext.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); return result; } private class ExclusiveSynchronizationContext : SynchronizationContext { // ... 为简洁起见省略了实现细节 } }
This solution works well under the condition that the asynchronous method is required to run asynchronous.
The above is the detailed content of How to Synchronously Run an Async Task Method in C#?. For more information, please follow other related articles on the PHP Chinese website!