C# Asynchronous Programming Async & Await

Level : Advanced
Mentor: Shailendra Chauhan
Duration : 00:03:00

Asynchronous Programming Patterns In .NET:

Asynchronous programming in .NET provides efficient ways to execute tasks concurrently, improving responsiveness. There are various patterns and techniques, including APM, EAP, and TAP, which offer different ways to handle asynchronous operations.

Asynchronous Programming Model (APM):

APM is one of the earliest asynchronous programming patterns in .NET. It involves methods with Begin and End prefixes, using callbacks for completion notification.


// APM example
FileStream fileStream = new FileStream("file.txt", FileMode.Open);
byte[] buffer = new byte[1024];
fileStream.BeginRead(buffer, 0, buffer.Length, ar =>
    int bytesRead = fileStream.EndRead(ar);
    // Process data here
}, null);

Task-based Asynchronous Programming (TAP):

TAP is a modern and recommended approach for asynchronous programming in .NET. It uses the Task and async/await keywords for clean and efficient asynchronous code.


// TAP example
async Task ReadFileAsync()
    using (FileStream fileStream = new FileStream("file.txt", FileMode.Open))
        byte[] buffer = new byte[1024];
        int bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length);
        // Process data here

Async Return Types:

Methods marked as async can have various return types, including Task, Task<T>, void, or custom types. This flexibility allows you to work with different types of asynchronous operations.


async Task<int> PerformAsyncOperation()
    await Task.Delay(1000);
    return 42;

Async and Await in TAP:

The async keyword is used to mark a method as asynchronous, and the await keyword is used to pause execution until an awaited task completes. This combination simplifies asynchronous code readability.


async Task MainAsync()
    int result = await PerformAsyncOperation();
    Console.WriteLine("Result: " + result);
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
Accept cookies & close this