Calling async method synchronously

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;
}

12 Answers
12

Leave a Comment