await and
Task.Wait in asynchronous programming: Deadlock trap
]
In asynchronous programming, it is crucial to understand the difference between await
and Task.Wait
. This article will analyze a case where the deadlock is caused by using Task.WaitAll
.
Task.Wait
: Synchronous blocking
Task.Wait
will block the current thread synchronously until the task is completed. In the example code,
Task.WaitAll waits for all 10 tasks returned by the
Ros()
await: Asynchronous wait
]
allows the method to return unfinished tasks to the caller while waiting for the task to complete asynchronously. When the task is completed, the remaining code in the method is scheduled for subsequent operations.
Deadlock Scene]
In the
sample code, the Get
method blocks the thread by calling Task.WaitAll
, and the Ros
method calls the asynchronous methods Foo
and Bar
] to create a series of asynchronous operations. This effectively prevents the task from completing and freeing the thread. As a result, the
method will never exit, resulting in a deadlock.
Blocking operation in asynchronous code]The use of blocking operations in asynchronous code is not generally recommended. When blocking occurs, the thread cannot process incoming requests, resulting in performance degradation and possible deadlocks.
in conclusion
Understanding the difference between await
and Task.Wait
is crucial to avoid deadlocks and effectively leveraging asynchronous programming. Task.Wait
should be used only in specific scenarios where synchronous blocking is required. In most cases, it is recommended to use a "fully asynchronous" approach, using
throughout your code to maintain asynchronousness and prevent blocking problems.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3