An async/await example that causes a deadlock

后端 未结 5 1917
暗喜
暗喜 2020-11-21 13:32

I came across some best practices for asynchronous programming using c#\'s async/await keywords (I\'m new to c# 5.0).

One of the advices gi

5条回答
  •  旧巷少年郎
    2020-11-21 14:09

    I was just fiddling with this issue again in an ASP.NET MVC project. When you want to call async methods from a PartialView, you're not allowed to make the PartialView async. You'll get an exception if you do.

    You can use the following simple workaround in the scenario where you want to call an async method from a sync method:

    1. Before the call, clear the SynchronizationContext
    2. Do the call, there will be no more deadlock here, wait for it to finish
    3. Restore the SynchronizationContext

    Example:

    public ActionResult DisplayUserInfo(string userName)
    {
        // trick to prevent deadlocks of calling async method 
        // and waiting for on a sync UI thread.
        var syncContext = SynchronizationContext.Current;
        SynchronizationContext.SetSynchronizationContext(null);
    
        //  this is the async call, wait for the result (!)
        var model = _asyncService.GetUserInfo(Username).Result;
    
        // restore the context
        SynchronizationContext.SetSynchronizationContext(syncContext);
    
        return PartialView("_UserInfo", model);
    }
    

提交回复
热议问题