Using "async" (even if it should complete) as part of a MVC route deadlocks the route; how can this be avoided?
It's to do with the way the synchronization context is implemented in ASP.NET (Pre .NET 4.5). There's tons of questions about this behavior:
Task.WaitAll hanging with multiple awaitable tasks in ASP.NET
Asp.net SynchronizationContext locks HttpApplication for async continuations?
In ASP.NET 4.5, there's a new implementation of the sync context that's described in this article.
http://blogs.msdn.com/b/webdev/archive/2012/11/19/all-about-httpruntime-targetframework.aspx
When you use .Result
there is always a possibility of deadlock because .Result
is blocking by nature. The way to avoid deadlocks is to not block on Tasks (you should use async
and await
all the way down). The subject is in details described here:
One fix is to add ConfigureAwait
:
public static async Task<long> IndirectSlowDouble(long val){ long result = await SlowDouble(val).ConfigureAwait(false); return result;}
Another fix is to use async
/await
throughout:
public async Task<ActionResult> Index(){ var task = IndirectSlowDouble(10); long result = await task; ViewBag.Message = result.ToString(); return View();}