How to call asynchronous method from synchronous method in C#?

后端 未结 15 1056
星月不相逢
星月不相逢 2020-11-21 06:27

I have a public async void Foo() method that I want to call from synchronous method. So far all I have seen from MSDN documentation is calling async methods via

15条回答
  •  情话喂你
    2020-11-21 06:39

    Inspired by some of the other answers, I created the following simple helper methods:

    public static TResult RunSync(Func> method)
    {
        var task = method();
        return task.GetAwaiter().GetResult();
    }
    
    public static void RunSync(Func method)
    {
        var task = method();
        task.GetAwaiter().GetResult();
    }
    

    They can be called as follows (depending on whether you are returning a value or not):

    RunSync(() => Foo());
    var result = RunSync(() => FooWithResult());
    

    Note that the signature in the original question public async void Foo() is incorrect. It should be public async Task Foo() as you should return Task not void for async methods that don't return a value (yes, there are some rare exceptions).

提交回复
热议问题