C# provides built-in support for asynchronous programming through the async and await keywords. They allow developers to write code that performs non-blocking operations, such as file I/O, network calls or database queries, without freezing the main thread.
Asynchronous programming improves application responsiveness, especially in UI-based and server-side applications where blocking operations can degrade performance.
Key Points
- async and await simplify writing asynchronous code.
- The async modifier is applied to a method, lambda or anonymous function.
- The await keyword is used inside an async method to pause execution until the awaited task is complete.
- An async method usually returns Task, Task<TResult> or void (only for event handlers).
- Execution does not block the calling thread while awaiting a task.
Syntax
async Task MethodName()
{
await SomeAsyncOperation();
}
How Async and Await Work
- The method marked with async can use await inside its body.
- When await is encountered, the control is returned to the caller until the awaited task finishes.
- After completion, execution resumes from the point where it was paused.
Example 1: Asynchronous File Read
Explanation:
- ReadFileAsync is marked with async and returns Task<string>.
- ReadToEndAsync is awaited, so the method does not block the main thread.
- The program reads the file content asynchronously.
Example 2: Simulating Delay
Output:
Task started...
Task finished after delay.
Here, Task.Delay simulates a non-blocking pause without freezing the program.
Example 3: Async with Return Type