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