Consider the following (based on the default MVC template), which is a simplified version of some "stuff" that happens in the background - it completes fine, and shows the expected result, 20:
public ActionResult Index()
{
var task = SlowDouble(10);
string result;
if (task.Wait(2000))
{
result = task.Result.ToString();
}
else
{
result = "timeout";
}
ViewBag.Message = result;
return View();
}
internal static Task<long> SlowDouble(long val)
{
TaskCompletionSource<long> result = new TaskCompletionSource<long>();
ThreadPool.QueueUserWorkItem(delegate
{
Thread.Sleep(50);
result.SetResult(val * 2);
});
return result.Task;
}
However, now if we add some async
into the mix:
public static async Task<long> IndirectSlowDouble(long val)
{
long result = await SlowDouble(val);
return result;
}
and change the first line in the route to:
var task = IndirectSlowDouble(10);
then it does not work; it times out instead. If we add breakpoints, the return result;
in the async
method only happens after the route has already completed - basically, it looks like the system is unwilling to use any thread to resume the async
operation until after the request has finished. Worse: if we had used .Wait()
(or accessed .Result
), then it will totally deadlock.
So: what is with that? The obvious workaround is "don't involve async
", but that is not easy when consuming libraries etc. Ultimately, there is no functional difference between SlowDouble
and IndirectSlowDouble
(although there is obvious a structural difference).
Note: the exact same thing in a console / winform / etc will work fine.