问题
Suppose I'm writing a custom MVC filter which does some asynchronous calls within the method overrides, like so:
public class MyActionFilter : System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext ctx)
{
var stuff = ConfigureAwaitHelper1().Result;
// do stuff
}
public override void OnActionExecuting(ActionExecutingContext ctx)
{
var stuff = ConfigureAwaitHelper2().Result;
// do stuff
}
private async Task<string> ConfigureAwaitHelper1()
{
var result = await client.GetAsStringAsync("blah.com").ConfigureAwait(false);
return result;
}
private async Task<string> ConfigureAwaitHelper2()
{
return await client.GetAsStringAsync("blah.com").ConfigureAwait(false);
}
}
Why does OnActionExecuting
deadlock, whereas OnActionExecuted
does not? I don't see the fundamental difference between the two. The act of returning happens only after the asynchronous task is complete, which is rather like putting the result into an "anonymous return" local var before returning it, so I don't see why the former should deadlock.
回答1:
Why does OnActionExecuting deadlock, whereas OnActionExecuted does not?
I'm surprised it works at all. The reason you're experiencing the deadlock is due to the fact that you're invoking a .Result
on a Task
. This is evil and you should only ever invoke .Result
and .Wait
in console applications.
来源:https://stackoverflow.com/questions/38446331/deadlock-with-async-await