c# async await
Asynchronous programming
Task asynchronous programming model
An async method runs synchronously until it reaches its first await expression, at which point the method is suspended until the awaited task is complete. In the meantime, control returns to the caller of the method, as the example in the next section shows.
key points
C# supports simplified approach, async programming, that leverages asynchronous support in the .NET runtime. The compiler does the difficult work that the developer used to do, and your application retains a logical structure that resembles synchronous code. As a result, you get all the advantages of asynchronous programming with a fraction of the effort.
await: The method usually includes at least one await expression, which marks a point where the method can’t continue until the awaited asynchronous operation is complete. In the meantime, the method is suspended, and control returns to the method’s caller. The marked async method can use await to designate suspension points. The await operator tells the compiler that the async method can’t continue past that point until the awaited asynchronous process is complete. In the meantime, control returns to the caller of the async method.
When the await operator is applied to the operand that represents an already completed operation, it returns the result of the operation immediately without suspension of the enclosing method.
Thread
Async methods are intended to be non-blocking operations. An await expression in an async method doesn’t block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.
The async and await keywords don’t cause additional threads to be created. Async methods don’t require multithreading because an async method doesn’t run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.
Example
1 | using System.Threading.Tasks; |
- 标题: c# async await
- 作者: cyang812
- 创建于 : 2022-12-05 12:55:23
- 更新于 : 2022-12-05 12:55:23
- 链接: https://blog.cyang.tech/2022/12/05/csharp async await/
- 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。