asynchronous programming:
Comparison with and potential dead locks await
Task.WaitAll
The difference between and
Task.Wait
await
In this scene, the "get" method is expected to have a deadlock. What is the fundamental reason? What is the difference between using obstruction and waiting rather than
<code class="language-csharp">public async Task<string> Foo() { await Task.Delay(1).ConfigureAwait(false); return ""; } public async static Task<string> Bar() { return await Foo(); } public async static Task<string> Ros() { return await Bar(); } public IEnumerable<string> Get() { Task.WaitAll(Enumerable.Range(0, 10).Select(x => Ros()).ToArray()); return new string[] { "value1", "value2" }; // 由于死锁而从未执行 }</code>
Differences: await Task.Delay
and
Wait
and await
assume similar conceptual roles, but their functions are different. will block the current thread until the task is completed. This method is not advisable because it starves the thread pool.
On the contrary, will be paused asynchronous to execute methods. The current state of the method is captured, and this method will return its unfinished tasks to the caller. After the task is completed, the rest of the method will be scheduled as a continuation. Task.Wait
await
Task.Wait
The potential dead locks of and asynchronous missions
await
In the code fragment provided, the "get" method calls
, which will suspend its execution. As a result, the task was not completed, and the thread was still blocked in the call. This will cause dead locks. Task.WaitAll
Use asynchronous programming to avoid dead locks
Task.WaitAll
In order to solve this problem, asynchronous programming must be used, especially when dealing with delay and suspension tasks. By combining the use of and await Foo
keywords, the code can maintain the response ability and prevent dead locks. WaitAll
The above is the detailed content of Async Programming: `Task.WaitAll` Deadlock: What Causes It and How Does It Differ from Using `await`?. For more information, please follow other related articles on the PHP Chinese website!