异步/等待死锁 [英] Deadlock with async/await

查看:132
本文介绍了异步/等待死锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在编写一个自定义MVC过滤器,该过滤器在方法覆盖中执行一些异步调用,如下所示:

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);
  }
}

为什么OnActionExecuting会死锁,而OnActionExecuted不会死锁?我看不出两者之间的根本区别.返回操作仅在异步任务完成后才发生,这就像在将结果返回之前将结果放入匿名返回"本地var中一样,所以我不明白为什么前者应该死锁.

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.

推荐答案

为什么OnActionExecuting死锁,而OnActionExecuted没有死锁?

Why does OnActionExecuting deadlock, whereas OnActionExecuted does not?

我很惊讶它完全起作用.遇到死锁的原因是由于您正在调用Task上的.Result.这是邪恶的,您只应在控制台应用程序中调用.Result.Wait.

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.

这篇关于异步/等待死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆