2017-09-04 79 views
0

我認爲我的網絡應用程序在調用YouTube API服務時遇到了死鎖,所以我想知道如何以正確的方式解決此問題。我懷疑這是一個類似的情況如下:Why does this async action hang?MVC5 - 具有異步任務的死鎖?

請有人建議,很簡單的話,爲什麼我的Web應用程序掛起(見行內評論),以及它應該如何正確解決?謝謝!

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

等待調用UpdateVideoOnYoutTube方法和刪除訪問'Result'廣告載體 – Shyju

+0

但後來我想的ActionResult將需要同步?這是正確的和良好的做法? –

+4

是讓它'異步任務 Shyju

回答

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