Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using httpclient in MVC application [duplicate]

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;
}
like image 913
ragche Avatar asked Dec 17 '13 05:12

ragche


1 Answers

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
like image 74
Stephen Cleary Avatar answered Sep 30 '22 17:09

Stephen Cleary