最佳答案
我偶然发现了一些使用 c # 的 async/await关键字进行异步编程的最佳实践(我是 c # 5.0的新手)。
其中一项建议如下:
稳定性: 了解您的同步上下文
一些同步上下文是不可重入的和单线程的。这意味着在给定的时间只能在上下文中执行一个工作单元。这方面的一个例子是 WindowsUI 线程或 ASP.NET 请求上下文。 在这些单线程同步上下文中,很容易出现死锁。如果从单线程上下文派生任务,然后在上下文中等待该任务,则等待代码可能会阻塞后台任务。
public ActionResult ActionAsync()
{
// DEADLOCK: this blocks on the async task
var data = GetDataAsync().Result;
return View(data);
}
private async Task<string> GetDataAsync()
{
// a very simple async method
var result = await MyWebService.GetDataAsync();
return result.ToString();
}
If I try to dissect it myself, the main thread spawns to a new one in MyWebService.GetDataAsync();, but since the main thread awaits there, it waits on the result in GetDataAsync().Result. Meanwhile, say the data is ready. Why doesn't the main thread continue it's continuation logic and returns a string result from GetDataAsync() ?
有人能解释一下为什么上面的例子会出现僵局吗? I'm completely clueless about what the problem is ...