Calling async method synchronously

Catalin picture Catalin · Mar 25, 2014 · Viewed 250.7k times · Source

I have an async method:

public async Task<string> GenerateCodeAsync()
{
    string code = await GenerateCodeService.GenerateCodeAsync();
    return code;
}

I need to call this method from a synchronous method.

How can I do this without having to duplicate the GenerateCodeAsync method in order for this to work synchronously?

Update

Yet no reasonable solution found.

However, i see that HttpClient already implements this pattern

using (HttpClient client = new HttpClient())
{
    // async
    HttpResponseMessage responseAsync = await client.GetAsync(url);

    // sync
    HttpResponseMessage responseSync = client.GetAsync(url).Result;
}

Answer

Heinzi picture Heinzi · Mar 25, 2014

You can access the Result property of the task, which will cause your thread to block until the result is available:

string code = GenerateCodeAsync().Result;

Note: In some cases, this might lead to a deadlock: Your call to Result blocks the main thread, thereby preventing the remainder of the async code to execute. You have the following options to make sure that this doesn't happen:

This does not mean that you should just mindlessly add .ConfigureAwait(false) after all your async calls! For a detailed analysis on why and when you should use .ConfigureAwait(false), see the following blog post: