http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

This is a problem that is brought up repeatedly on the forums and Stack Overflow. I think it’s the most-asked question by async newcomers once they’ve learned the basics.

UI Example

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).

// My "library" method.
public static async Task<JObject> GetJsonAsync(Uri uri)
{
using (var client = new HttpClient())
{
var jsonString = await client.GetStringAsync(uri);
return JObject.Parse(jsonString);
}
} // My "top-level" method.
public void Button1_Click(...)
{
var jsonTask = GetJsonAsync(...);
textBox1.Text = jsonTask.Result;
}

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.

ASP.NET Example

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):

// My "library" method.
public static async Task<JObject> GetJsonAsync(Uri uri)
{
using (var client = new HttpClient())
{
var jsonString = await client.GetStringAsync(uri);
return JObject.Parse(jsonString);
}
} // My "top-level" method.
public class MyController : ApiController
{
public string Get()
{
var jsonTask = GetJsonAsync(...);
return jsonTask.Result.ToString();
}
}

This code will also deadlock. For the same reason.

What Causes the Deadlock

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 does only 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):

  1. The top-level method calls GetJsonAsync (within the UI/ASP.NET context).
  2. GetJsonAsync starts the REST request by calling HttpClient.GetStringAsync (still within the context).
  3. GetStringAsync returns an uncompleted Task, indicating the REST request is not complete.
  4. GetJsonAsync awaits the Task returned by GetStringAsync. The context is captured and will be used to continue running the GetJsonAsync method later. GetJsonAsync returns an uncompleted Task, indicating that the GetJsonAsync method is not complete.
  5. The top-level method synchronously blocks on the Task returned by GetJsonAsync. This blocks the context thread.
  6. … Eventually, the REST request will complete. This completes the Task that was returned by GetStringAsync.
  7. The continuation for GetJsonAsync is now ready to run, and it waits for the context to be available so it can execute in the context.
  8. Deadlock. The top-level method is blocking the context thread, waiting for GetJsonAsync to complete, and GetJsonAsync is waiting for the context to be free so it can complete.

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”.

Preventing the Deadlock

There are two best practices (both covered in my intro post) that avoid this situation:

  1. In your “library” async methods, use ConfigureAwait(false) wherever possible.
  2. Don’t block on Tasks; use async all the way down.

Consider the first best practice.   //UI的修改

The new “library” method looks like this:

public static async Task<JObject> GetJsonAsync(Uri uri)
{
using (var client = new HttpClient())
{
var jsonString = await client.GetStringAsync(uri).ConfigureAwait(false);
return JObject.Parse(jsonString);
}
}

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.     //ASP.NET的修改

The new “top-level” methods look like this:

public async void Button1_Click(...)
{
var json = await GetJsonAsync(...);
textBox1.Text = json;
} public class MyController : ApiController
{
public async Task<string> Get()
{
var json = await GetJsonAsync(...);
return json.ToString();
}
}

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.

Resources

This kind of deadlock is always the result of mixing synchronous with asynchronous code.

Usually this is because people are just trying out async with one small piece of code and use synchronous code everywhere else.

Unfortunately, partially-asynchronous code is much more complex and tricky than just making everything asynchronous.

If you do need to maintain a partially-asynchronous code base, then be sure to check out two more of Stephen Toub’s blog posts:Asynchronous Wrappers for Synchronous Methods and Synchronous Wrappers for Asynchronous Methods, as well as my AsyncEx library.

Answered Questions

There are scores of answered questions out there that are all caused by the same deadlock problem. It has shown up on WinRT, WPF, Windows Forms, Windows Phone, MonoDroid, Monogame, and ASP.NET.

Update (2014-12-01): For more details, see my MSDN article on asynchronous best practices or Section 1.2 in myConcurrency Cookbook.

还有一个姊妹篇http://blog.stephencleary.com/2012/12/dont-block-in-asynchronous-code.html

Don't Block on Async Code的更多相关文章

  1. Async方法死锁的问题 Don't Block on Async Code(转)

    今天调试requet.GetRequestStreamAsync异步方法出现不返回的问题,可能是死锁了.看到老外一篇文章解释了异步方法死锁的问题,懒的翻译,直接搬过来了. http://blog.st ...

  2. Don't Block on Async Code【转】

    http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html This is a problem that is brough ...

  3. Practical Node.js (2018版) 14章, async code in Node

    Asynchronous Code in Node 历史上,Node开发者只能用回调和事件emitters. 现在可以使用一些异步的语法: async module Promises Async/aw ...

  4. Async All the Way

    Asynchronous code reminds me of the story of a fellow who mentioned that the world was suspended in ...

  5. ASP.NET sync over async(异步中同步,什么鬼?)

    async/await 是我们在 ASP.NET 应用程序中,写异步代码最常用的两个关键字,使用它俩,我们不需要考虑太多背后的东西,比如异步的原理等等,如果你的 ASP.NET 应用程序是异步到底的, ...

  6. Async/Await - Best Practices in Asynchronous Programming

    https://msdn.microsoft.com/en-us/magazine/jj991977.aspx Figure 1 Summary of Asynchronous Programming ...

  7. 小心C# 5.0 中的await and async模式造成的死锁

    平时在使用C# 5.0中的await and async关键字的时候总是没注意,直到今天在调试一个ASP.NET项目时,发现在调用一个声明为async的方法后,程序老是莫名其妙的被卡住,就算声明为as ...

  8. Async/Await - Best Practices in Asynchronous Programming z

    These days there’s a wealth of information about the new async and await support in the Microsoft .N ...

  9. async/await 的一些知识

    博文 Don't Block on Async Code What is the purpose of "return await" in C#? Any difference b ...

随机推荐

  1. SDOI 2018 round2游记

    Day 0 早上起来从北京到济南 住宿环境不错 不过比赛环境怎么这么low啊 而且我在最偏僻的考场中最偏僻的角落里 身边居然是个妹子?! Day1 7:40到的考试地点 发现诸位大佬已经打完板子了or ...

  2. C# 如何实现WinForm程序自重启(重新启动自己)

    重启的时间间隔方法 private void Restart() { Thread thtmp = new Thread(new ParameterizedThreadStart(run)); obj ...

  3. JDBC的详细使用

    1.首先说一下需要用到的工具: ①我这里用的数据库是MySql5.6 ,MySql6.0开始被Oracle收购需要付费了,6.0以下版本免费. ②去Maven仓库下载JDBC的jar包 Maven仓库 ...

  4. crontab与系统时间不一致

    将线上数据库迁移至虚拟机后,运维没有把时间修改. 在后期把时间修改完成后,在数据库上也要修改修改,但是定时任务的备份时间却不在凌晨4点执行,而是在中午12:10分执行. 原因是修改时间后,需要重启cr ...

  5. Metric Learning度量学习:**矩阵学习和图学习

    DML学习原文链接:http://blog.csdn.net/lzt1983/article/details/7884553 一篇metric learning(DML)的综述文章,对DML的意义.方 ...

  6. cmd 运行 svn 亲测!!!

    如果之前安装了svn客户端,但是一直提示svn停止工作的话就可以用cmd去操作svn更新和提交了:或者可以直接用别的代码IDE(包含svn插件的)去进行svn的操作. 接下来我说说windows如何用 ...

  7. 范畴论-一个单子(Monad)说白了不过就是自函子范畴上的一个幺半群而已

    范畴即为结构:包含要素和转化. 范畴为高阶类型. 函子为高阶函数.函子的输入为态射.函子为建立在态射基础上的高阶函数.函子用于保持范畴间映射的结构.态射用于范畴内部的转换. 群为运算规则的约束. 自函 ...

  8. Cache-Control 机制是为浏览器定制的?

    Cache-Control 机制是为浏览器定制的?

  9. py西游公关之模块

    Py西游攻关之模块   模块&包(* * * * *) 模块(modue)的概念: 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可 ...

  10. 51nod1085 背包问题【动态规划】

    在N件物品取出若干件放在容量为W的背包里,每件物品的体积为W1,W2--Wn(Wi为整数),与之相对应的价值为P1,P2--Pn(Pi为整数).求背包能够容纳的最大价值. Input 第1行,2个整数 ...