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

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

    You can call any asynchronous method from synchronous code, that is, until you need to await on them, in which case they have to be marked async too.

    As a lot of people are suggesting here, you could call Wait() or Result on the resulting task in your synchronous method, but then you end up with a blocking call in that method, which sort of defeats the purpose of async.

    I you really can't make your method async and you don't want to lock up the synchronous method, then you're going to have to use a callback method by passing it as parameter to the ContinueWith method on task.

提交回复
热议问题