and The cause of the deadlock await
.Result
When using asynchronous operations in C#, it is important to understand the potential trap of mixed synchronization and asynchronous calls. In this example, due to the following code line, the last test hangs due to dead locks:
The reason for the deadlock
Assert.IsTrue(CheckStatus().Result); // 导致挂起
<一> is an asynchronous method that returns a Boolean type task.
CheckStatus()
Result
This leads to a deadlock: asynchronous method is trying to continue execution on the main thread, and the main thread is waiting for the task to complete. The following code demonstrates the correct usage of :
await
<免> Avoid directly calling
await
[Test] public async Task CheckStatusTwiceResultTest() { Assert.IsTrue(await CheckStatus()); Assert.IsTrue(await CheckStatus()); }
directly on the task. Instead, rely on the mode to ensure that asynchronous operations are performed in non -blocking.
Result
Conclusion
By understanding the potential consequences of mixing synchronization and asynchronous calls, developers can effectively use the asynchronous methods in C#without encountering dead locks or performance problems. Result
The above is the detailed content of Why Does Mixing `await` and `.Result` in C# Async Operations Cause Deadlocks?. For more information, please follow other related articles on the PHP Chinese website!