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