Search code examples
asp.netasync-awaitiis-express

ASP.NET call hangs on async await


My calls to a Google API from an API Controller in IIS express hang indefinitely when called sequentially using async await.

var id = CreateDocument("My Title").Result;

async Task<string> CreateDocument(string title)
{
    var file = new GData.File { Title = title };
    // Stepping over this line in the debugger never returns in IIS Express.
    file = await Service.Files.Insert(file).ExecuteAsync();
    return file.Id;
}

It does not hang calling the same method from a test console app.

The same logic also does not hang IIS Express when called using the corresponding synchronous method instead.

var id = CreateDocument("My Title");

string CreateDocument(string title)
{
    var file = new GData.File { Title = title };
    // This has no problem
    file = Service.Files.Insert(file).Execute();
    return file.Id;
}

Where should I look for the defect?


Solution

  • The defect is here:

    var id = CreateDocument("My Title").Result;
    

    As I explain on my blog, you should not block on async code.

    Instead of Result, use await:

    var id = await CreateDocument("My Title");