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

后端 未结 15 1101
星月不相逢
星月不相逢 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 07:04

    After hours of trying different methods, with more or less success, this is what I ended with. It doesn't end in a deadlock while getting result and it also gets and throws the original exception and not the wrapped one.

    private ReturnType RunSync()
    {
      var task = Task.Run(async () => await myMethodAsync(agency));
      if (task.IsFaulted && task.Exception != null)
      {
        throw task.Exception;
      }
    
      return task.Result;
    }
    

提交回复
热议问题