Deadlock with async/await

妖精的绣舞 提交于 2019-12-10 18:46:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!