MVC5 - 异步任务死锁?

时间:2017-09-04 20:52:11

标签: asp.net-mvc asp.net-mvc-5 async-await deadlock

我认为我的网络应用程序在调用YouTube API服务时遇到了僵局,所以我想知道如何以正确的方式解决这个问题。我怀疑它与以下类似的情况:Why does this async action hang?

有人可以用非常简单的术语告诉我为什么我的网络应用程序会挂起(请参阅内联注释)以及如何正确解析它?谢谢!

public ActionResult Index()
{
    YouTubeHelper yth = new YouTubeHelper();
     bool unpublishVideo = yth.UpdateVideoOnYouTube(17, "public").Result;
}

public async Task<bool> UpdateVideoOnYouTube(int propertyId, string publishStatus)
{
.....
    YouTubeService youtubeService = await GetYouTubeService(db);
.....
}

public async Task<YouTubeService> GetYouTubeService(ApplicationDbContext db)
{
....
    if (!await credential.RefreshTokenAsync(CancellationToken.None)) //It hangs here!!
        {
        ....
    }
....
}

1 个答案:

答案 0 :(得分:2)

解释了死锁here。总之,您的异步方法在完成之前需要ASP.NET请求上下文,但是对Result的调用阻止了ASP.NET请求上下文,直到异步方法已经完成。

为避免死锁,请不要阻止异步代码。使用await代替Result

public async Task<ActionResult> Index()
{
  YouTubeHelper yth = new YouTubeHelper();
  bool unpublishVideo = await yth.UpdateVideoOnYouTube(17, "public");
}
相关问题