6

When I invoke below function in a console app, it just works. But when I add the same to a MVC controller, execution never reaches JsonConvert line. Any idea, what I am missing.

Calling code

GetVersion(url).Result.FileVersion

Method

public static async Task<Version> GetVersion(string url, string hostHeader)
{
    var client = new HttpClient();
    if (!string.IsNullOrEmpty(hostHeader))
    {
        client.DefaultRequestHeaders.Host = hostHeader;
    }
    var version = await client.GetStringAsync(url);
    var output = JsonConvert.DeserializeObject<Version>(version);
    client.Dispose();
    return output;
}
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
ragche
  • 443
  • 3
  • 11

1 Answers1

9

You are causing a deadlock, as I explain on my blog. By default, await captures a "context" (in this case, the ASP.NET request context) and uses that to resume the async method. The ASP.NET request context only allows one thread in at a time, and you're blocking that thread by calling Result, thus preventing the async method from completing.

Your console app doesn't deadlock because it doesn't have a "context", so the async methods resume on the thread pool.

The solution is to change the calling code to use:

(await GetVersion(url)).FileVersion
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810