[转]小心C# 5.0 中的await and async模式造成的死锁
2021-04-12 23:28
标签:resume htm ble imp ges blog prevent 需要 tool https://www.cnblogs.com/OpenCoder/p/4434574.html 内容 Consider the example below. A button click will initiate a REST call and display the results in a text box (this sample is for Windows Forms, but the same principles apply to any UI application). The “GetJson” helper method takes care of making the actual REST call and parsing it as JSON. The button click handler waits for the helper method to complete and then displays its results. This code will deadlock. This example is very similar; we have a library method that performs a REST call, only this time it’s used in an ASP.NET context (Web API in this case, but the same principles apply to any ASP.NET application): This code will also deadlock. For the same reason. Here’s the situation: remember from my intro post that after you await a Task, when the method continues it will continue in a context. In the first case, this context is a UI context (which applies to any UI except Console applications). In the second case, this context is an ASP.NET request context. One other important point: an ASP.NET request context is not tied to a specific thread (like the UI context is), but it doesonly allow one thread in at a time. This interesting aspect is not officially documented anywhere AFAIK, but it is mentioned in my MSDN article about SynchronizationContext. So this is what happens, starting with the top-level method (Button1_Click for UI / MyController.Get for ASP.NET): For the UI example, the “context” is the UI context; for the ASP.NET example, the “context” is the ASP.NET request context. This type of deadlock can be caused for either “context”. 上面内容的大致意思就是说在使用await and async模式时,await关键字这一行后面的代码块会被一个context(也就是上面提到的ASP.NET request contex和UI context)线程继续执行,如果我们将本例中调用top-level method的线程称为线程A(即context线程),由于GetJsonAsync方法也是由线程A调用的,所以当GetJsonAsync方法中await的GetStringAsync方法执行完毕后,GetJsonAsync需要重新使用线程A执行await代码行之后的代码,而现在由于线程A在top-level method的代码中因为访问了jsonTask.Result被阻塞了(因为线程A调用top-level method代码中jsonTask.Result的时候,await的GetStringAsync的Task还没执行完毕,所以被线程A阻塞),所以GetJsonAsync无法重新使用线程A执行await代码行之后的代码块,也被阻塞,所以形成了死锁。也就是说top-level method代码中线程A因为等待GetJsonAsync中await的GetStringAsync结束被阻塞,而GetStringAsync也等待线程A在top-level method的阻塞结束获得线程A来执行GetJsonAsync中await代码行后面的代码也被阻塞,两个阻塞相互等待,相互死锁。 There are two best practices (both covered in my intro post) that avoid this situation: 这里我补充一下,如果你开发的是Winform程序,那么最好用第二种方法避免死锁,也就是不要阻塞主线程,这样当await等待的Task对象线程执行完毕后,由于主线程没有被阻塞,因此await后面的代码就会在恰当的时候(这里提到的“恰当的时候”是由.Net Framework自己判断的,.Net Framework会安排主线程在某个时候继续执行await后面的代码)继续在主线程上执行完毕。之所以在Winform中不推荐用第一种方法是因为第一种方法会让await后面的代码在另外的线程上执行,而不再是在主线程上执行,如果await后有代码设置了Winform控件的值,那么会引起Winform程序的线程安全问题,所以在Winform中最好的办法还是不要阻塞主线程,让await后面的代码能够在主线程上执行。但在Asp.net中用上面第一种或第二种方法都可以,不存在线程安全问题。 Consider the first best practice. The new “library” method looks like this: This changes the continuation behavior of GetJsonAsync so that it does not resume on the context. Instead, GetJsonAsync will resume on a thread pool thread. This enables GetJsonAsync to complete the Task it returned without having to re-enter the context. Consider the second best practice. The new “top-level” methods look like this: This changes the blocking behavior of the top-level methods so that the context is never actually blocked; all “waits” are “asynchronous waits”. Note: It is best to apply both best practices. Either one will prevent the deadlock, but both must be applied to achieve maximum performance and responsiveness. The third best practice:如果想结束async & await模式的调用,启动一个新的线程去await异步方法的返回结果 这样因为GetJsonAsync方法是由Task.Run新启动的线程来调用的,所以在await GetJsonAsync(...)执行完毕之后,.Net Framework就会用Task.Run新启动的线程来执行await之后的代码,不会和top-level method的线程(即context线程)相互阻塞,造成死锁。 最后再补充说一点,本文提到的await and async死锁问题,在.Net控制台程序中并不存在。因为经过实验发现在.Net控制台程序中,await关键字这一行后面的代码默认就是在一个新的线程上执行的,也就是说在控制台程序中就算不调用Task.ConfigureAwait(false),await关键字这一行后面的代码也会在一个新启动的线程上执行,不会和主线程发生死锁。但是在Winform和Asp.net中就会发生死锁。 [转]小心C# 5.0 中的await and async模式造成的死锁 标签:resume htm ble imp ges blog prevent 需要 tool 原文地址:https://www.cnblogs.com/wolf-sun/p/8989430.html原文链接
UI Example
// My "library" method.
public static async Task
ASP.NET Example
// My "library" method.
public static async Task
What Causes the Deadlock
Preventing the Deadlock
public static async Task
public async void Button1_Click(...)
{
var json = await GetJsonAsync(...);
textBox1.Text = json;
}
public class MyController : ApiController
{
public async Task
// My "library" method.
public static async Task
文章标题:[转]小心C# 5.0 中的await and async模式造成的死锁
文章链接:http://soscw.com/index.php/essay/74935.html