Home >Backend Development >C++ >Await vs. Task.Wait: Why Does Using Task.Wait Cause Deadlocks?
await
: The root of the deadlock Task.Wait
The difference in asynchronous programming is slightly important. This article explores the differences between the two and analyzes the common deadlock scenes. await
Task.Wait
task.wait: synchronous blocking
Cover the calling thread simultaneously until the task is completed. This essentially suspended the thread and waited for the task to be executed.
Task.Wait
The execution of the current method asynchronous. The state of the method was captured, and an unfinished task returned to the caller. When the waiting expression is completed, the remaining part of the method is scheduled to be continuously operated. Dead lock scene
await
Considering the following code examples, in which the error uses
In this code, the
method blocks the current thread, waiting for all the tasks in the collection to complete. However, each method contains a expression that hangs its execution. Task.Wait
<code>Task.WaitAll(Enumerable.Range(0, 10).Select(x => Ros()).ToArray());</code>, the
expression in the task cannot be completed. This generates dead locks because the task cannot continue to be executed unless the call is called to release its obstruction; the calling thread cannot release its obstruction, unless the task is completed. Task.WaitAll
Ros()
Why is the block waiting to avoid dead locks await
Using obstruction waiting, such as Task.WaitAll
or lock, it will not cause dead locks in this scene, because it will not prevent the task from being executed on a separate thread. The obstruction waiting is just the execution of the delay call method, allowing the task to continue and finally complete. await
To avoid dead locks, be sure to understand the difference between
and. Generally speaking, Thread.Sleep
is always used in asynchronous code to ensure that the calling thread is maintained.
The above is the detailed content of Await vs. Task.Wait: Why Does Using Task.Wait Cause Deadlocks?. For more information, please follow other related articles on the PHP Chinese website!