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

后端 未结 15 1053
星月不相逢
星月不相逢 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<T> or Task<HttpResponseMessage>... 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题