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

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

    To anyone paying attention to this question anymore...

    If you look in Microsoft.VisualStudio.Services.WebApi there's a class called TaskExtensions. Within that class you'll see the static extension method Task.SyncResult(), which like totally just blocks the thread till the task returns.

    Internally it calls task.GetAwaiter().GetResult() which is pretty simple, however it's overloaded to work on any async method that return Task, Task or Task... syntactic sugar, baby... daddy's got a sweet tooth.

    It looks like ...GetAwaiter().GetResult() is the MS-official way to execute async code in a blocking context. Seems to work very fine for my use case.

提交回复
热议问题