A trap about .net asynchronous programming

1.Code Sample & Result
What do you think about the result of the following codes?

I created a console project with the codes. The result is displayed as following:

It seems work well. But, I created a GUI project with the same codes. Calling the Test function in a message handler as following:

See the result as following:

It seems the codes are blocked at Task.Wait(). The windows is not responding.
2.Changed Sample & Result
Let's make a little changes as following:

I commented the calling of Task.Wait() in GUI project. See the result as following:

3.Changing Sample Code Again
If call the Test function in a user-created thread, how about the result? Let's change the sample again.

See the result as following:

The remaining part of asynchronous function after await keyword runs in the original thread automatically.
4.Analyzation
Comparing the difference of output between the 3 tests, we can find that the codes after await keyword runs in calling thread after asynchronous operation is completed in GUI process(if the asynchronous method is called in GUI thread). The calling thread is blocked by Task.Wait() and can't run the remaining part of asynchronous function after await keyword. It's the root cause of deadlock as following:

5.Solution
A simple solution is call the method Task.ConfigureAwait as following:

See the result as following:

The deadlock disappears. The remaining part of asynchronous function after await keyword is runned in the same thread as previous part. Please refer the article in 7th section for detailed solution.
6.Further Research
How does the process of the remaining part of asynchronous function after await keyword been transferred to the calling thread if we don't call the method ConfigureAwait? Let's seed the call stack while the asynchronous method is completed. We can find that the message mechanism supports the transfer between 2 threads.

7.References
《Async/Await - Best Practices in Asynchronous Programming》 https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值