Record the asynchronous understanding of. net and the asynchronous understanding of. net.
Recently I have been studying. net framwork is asynchronous. I have read a lot of blogs and learned a lot. But on MSDN, I am not very familiar with the deadlock caused by await on the UI. After thinking this morning, I feel restricted by the execution process of a single thread. Of course, I recorded my own thinking process.
First, post the MSDN Article address.
Https://msdn.microsoft.com/zh-cn/magazine/hh456402.aspx
And the code segment I previously asked
The following is a flowchart of understanding this logic.
Process description
First, the onlick event of the button is triggered, and the first step is to execute the main thread of the UI, and then reach the CopyStreamToStreamAsync method,
CopyStreamToStreamAsync method body
Before that, it was a synchronous thread. Later, CopyStreamToStreamAsync started asynchronous execution due to asynchronous reasons, and the main thread continued to execute until t. the main thread of the waiit () method is blocked. At this time, the context of the UI thread is not ignored in the Asynchronous Method. When the await method of the method body is reached, the asynchronous execution rule is
Capture context, that is, to return to the main UI thread. At this time, the main thread is blocked, and the wait () method itself is executed after the Task is executed, this will cause both parties to wait for each other to end unconditionally, resulting in deadlocks.
The solution on MSDN is to ignore the UI context, so that tasks can run in the context of the thread pool to avoid deadlocks.