Captain_Planet
Captain_Planet

Reputation: 1336

MVC5 - Deadlock with async Tasks?

I think my web application is suffering from deadlock when I'm calling YouTube API services, so I want to know how to resolve this in the correct manner. I suspect it's a similar scenario to the following: Why does this async action hang?

Please can somebody advise, in very simple terms, why my web application hangs (see inline comments) and how it should be correctly resolved? Thanks!

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!!
        {
        ....
    }
....
}

Upvotes: 0

Views: 583

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456537

The deadlock is explained here. In summary, your asynchronous methods are needing the ASP.NET request context before they can complete, but the call to Result is blocking the ASP.NET request context until the asynchronous methods are already completed.

To avoid the deadlock, don't block on async code. Use await instead of Result:

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

Upvotes: 2

Related Questions