Home > Backend Development > C++ > How to Synchronously Run an Async Task Method in C#?

How to Synchronously Run an Async Task Method in C#?

DDD
Release: 2025-02-01 07:16:08
Original
932 people have browsed it

How to Synchronously Run an Async Task Method in C#?

How to run asynchronous in C#

Method? Task<T>

In asynchronous programming, methods are usually defined as asynchronous tasks (

) 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>

Several methods of running asynchronous methods

One method is to use the

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()

Another choice is to use the

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()

Finally, you can use a solution involving scheduling program frames. Create a new , start it, and wait for tasks in Lambda expressions. After the task is completed, set the

attribute of the scheduling program to DispatcherFrame to stop the scheduling program pump. Continue false A reliable solution

A stronger solution is to use synchronous context, and the context will pump the message until the task is completed. This is a class that implements this 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
    {
        // ... 为简洁起见省略了实现细节
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template