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

后端 未结 15 1080
星月不相逢
星月不相逢 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:53

    async Main is now part of C# 7.2 and can be enabled in the projects advanced build settings.

    For C# < 7.2, the correct way is:

    static void Main(string[] args)
    {
       MainAsync().GetAwaiter().GetResult();
    }
    
    
    static async Task MainAsync()
    {
       /*await stuff here*/
    }
    

    You'll see this used in a lot of Microsoft documentation, for example: https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-how-to-use-topics-subscriptions

提交回复
热议问题