0 votes
20 views

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 async methods, but my whole program is not built with async methods.

Is this even possible?

Here's one example of calling these methods from an asynchronous method:
Walkthrough: Accessing the Web by Using Async and Await (C# and Visual Basic)

Now I'm looking into calling these async methods from sync methods.

1 Answer

0 votes

Stephen Cleary's Answer;

That approach shouldn't cause a deadlock (assuming that ProblemMethodAsync doesn't send updates to the UI thread or anything like that). It does assume that ProblemMethodAsync can be called on a thread pool thread, which is not always the case.

https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

And here is the approach;

The Thread Pool Hack A similar approach to the Blocking Hack is to offload the asynchronous work to the thread pool, then block on the resulting task. The code using this hack would look like the code shown in Figure 7.

Figure 7 Code for the Thread Pool Hack

C#

public sealed class WebDataService : IDataService
{
  public string Get(int id)
  {
    return Task.Run(() => GetAsync(id)).GetAwaiter().GetResult();
  }
  public async Task<string> GetAsync(int id)
  {
    using (var client = new WebClient())
      return await client.DownloadStringTaskAsync(
      "https://www.example.com/api/values/" + id);
  }
}

The call to Task.Run executes the asynchronous method on a thread pool thread. Here it will run without a context, thus avoiding the deadlock. One of the problems with this approach is the asynchronous method can’t depend on executing within a specific context. So, it can’t use UI elements or the ASP.NET HttpContext.Current.

...