25. Async and Await in C#
Level: Guided
- What problem async/await solves
- What
Taskmeans - Create async methods
- Use
await - Avoid
async void - Run multiple async tasks with
Task.WhenAll
Some work takes time:
- Reading from database
- Calling API
- Reading file
- Sending email
- Generating report
If code waits normally, the thread is blocked.
Async/await lets C# wait without blocking.
The Problem: Waiting Blocks Work
Synchronous style:
Request starts
Thread waits for database
Thread cannot do other work
Response returns
Async style:
Request starts
Database work starts
Thread is free for other work
Result comes back
Code continues
Quick Definitions
- Task - Work that will finish later (async operation)
- Async - Method that can use
await(works asynchronously) - Await - Wait for task without blocking thread
- Non-blocking - Thread stays free while waiting
- Blocking - Thread stuck waiting, cannot do other work
Task<T>- Task that returns a value of type T- WhenAll - Wait for multiple tasks together
async void- Avoid this (use async Task instead)- Synchronous - Code waits normally (blocking)
- Asynchronous - Code waits without blocking (thread stays free)
Why Async/Await Matters
Real problem:
School needs to load student data from database.
Without async:
Request arrives
Thread waits for database (locked)
Other students waiting (thread stuck)
Result returns
Thread finally free
With async:
Request arrives
Database work starts (thread free)
Other students served immediately (thread working)
Result comes back
Thread continues
Key insight: Thread stays busy helping other students while waiting.
What is Task?
Task represents work that will finish later.
| Return Type | Meaning |
|---|---|
Task | Async method returns no value |
Task<T> | Async method returns value of type T |
Example:
static async Task PrintMessageAsync()
{
await Task.Delay(1000);
Console.WriteLine("Done");
}
Example with value:
static async Task<string> GetStudentNameAsync()
{
await Task.Delay(1000);
return "Sahasra Kumar";
}
async and await
async allows a method to use await.
await waits for the task to finish without blocking the thread.
string name = await GetStudentNameAsync();
Console.WriteLine(name);
Full Example: Load Student Async
Task.WhenAll
Use Task.WhenAll when multiple async operations can run together.
Task<string> task1 = GetClassReportAsync("10-A");
Task<string> task2 = GetClassReportAsync("10-B");
string[] reports = await Task.WhenAll(task1, task2);
This is faster than waiting one by one.
Avoid async void
Wrong:
public async void LoadStudents()
{
await Task.Delay(1000);
}
Better:
public async Task LoadStudentsAsync()
{
await Task.Delay(1000);
}
Use async void only for UI event handlers.
When You'll Use This in SMS
Every slow operation needs async.
Real SMS scenarios:
// Load student from database
Student student = await GetStudentFromDatabaseAsync(rollNumber);
// Get all students asynchronously
List<Student> students = await LoadAllStudentsAsync();
// Generate report (slow)
string report = await GenerateReportAsync(className);
// Save marks to database
await SaveMarksAsync(studentId, marks);
// Call external API for fee payment gateway
bool paymentOk = await ProcessPaymentAsync(amount);
// Send email notifications
await SendEmailAsync(emailList);
// Multiple operations together
var reports = await Task.WhenAll(
GetClassReportAsync("10-A"),
GetClassReportAsync("10-B"),
GetClassReportAsync("10-C")
);
Real impact:
- Database query takes 500ms -> async = thread free to handle 10 other students
- SMS serving 100 students -> without async = blocked. With async = all served smoothly
- Production SMS runs 1000+ async operations daily
Key point: Slow operations (database, API, file) MUST be async. Otherwise server thread gets stuck.
Try This Now
Run the async student loader example above. Then experiment:
- Change
GetStudentAsyncto return different student names - Add sleep time:
await Task.Delay(2000);(simulate 2s database query) - Call multiple GetStudentAsync in parallel with
Task.WhenAll - Notice: multiple calls finish faster together than one by one
- Try removing
await(see how method starts but doesn't wait)
See how async lets multiple operations work together.
Async and await explained: Task, Task<T>, blocking vs non-blocking, WhenAll, avoiding async void. Video coming soon. Subscribe to NexCoding YouTube for updates.
Common Mistakes
Mistake 1: Calling async method without await
GetStudentAsync(101);
The method starts, but caller does not wait.
Correct:
Student student = await GetStudentAsync(101);
Mistake 2: Using .Result or .Wait()
Avoid blocking async code:
Student student = GetStudentAsync(101).Result;
Prefer:
Student student = await GetStudentAsync(101);
Mistake 3: Using async for normal CPU calculations
Async is mainly for waiting operations like database/API/file.
Best Practices
- Use
async Task, notasync void. - Always
awaitasync methods. - Add
Asyncsuffix to async method names. - Use
Task<T>when returning a value. - Use
Task.WhenAllfor independent async operations. - Do not use
.Resultor.Wait()in normal async code.
Practice Task
Create:
GetStudentAsync()GetTeacherAsync()- Call both using
Task.WhenAll - Print both names
Quick Revision
| Question | Answer |
|---|---|
| What is Task? | Work that finishes later |
| What does async do? | Allows await inside method |
| What does await do? | Waits without blocking |
| Async method with no value returns? | Task |
| Async method with value returns? | Task<T> |
| What should we avoid? | async void, .Result, .Wait() |
It allows code to wait for slow operations without blocking the thread.
Task represents an asynchronous operation that will complete later.
Task returns no value. Task<T> returns a value.
Caller cannot await it and exceptions are harder to handle. Use async Task.
It waits for multiple tasks to finish and lets them run together.
Use ChatGPT, Claude, or Copilot to go deeper on C# async await. Try these prompts:
"Explain async and await in simple words""Give me 5 practice tasks for async await""Explain Task and Task<T> simply""Quiz me with 5 beginner questions about async await"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.