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;
}
2
  • Which MVC Version are you using? Commented Dec 17, 2013 at 5:26
  • MVC4, .net4.5, vs2012 Commented Dec 17, 2013 at 5:26

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this works. I will read your blog in detail to understand more

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.