Skip to main content

25. Async and Await in C#

Level: Guided

ℹ️ What You'll Learn
  • What problem async/await solves
  • What Task means
  • 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 TypeMeaning
TaskAsync 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

💻 Try It — Console App
💡 Paste into Program.cs and press F5⌥ GitHub
Console.WriteLine("Loading student...");

Student student = await GetStudentAsync(101);

Console.WriteLine($"Student loaded: {student.Name}");

static async Task<Student> GetStudentAsync(int rollNumber)
{
await Task.Delay(1000);

return new Student
{
RollNumber = rollNumber,
Name = "Sahasra Kumar",
ClassName = "10-A"
};
}

public class Student
{
public int RollNumber { get; set; }
public string Name { get; set; } = "";
public string ClassName { get; set; } = "";
}

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:

  1. Change GetStudentAsync to return different student names
  2. Add sleep time: await Task.Delay(2000); (simulate 2s database query)
  3. Call multiple GetStudentAsync in parallel with Task.WhenAll
  4. Notice: multiple calls finish faster together than one by one
  5. Try removing await (see how method starts but doesn't wait)

See how async lets multiple operations work together.


ℹ️ Video Tutorial

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

  1. Use async Task, not async void.
  2. Always await async methods.
  3. Add Async suffix to async method names.
  4. Use Task<T> when returning a value.
  5. Use Task.WhenAll for independent async operations.
  6. Do not use .Result or .Wait() in normal async code.

Practice Task

Create:

  • GetStudentAsync()
  • GetTeacherAsync()
  • Call both using Task.WhenAll
  • Print both names

Quick Revision

QuestionAnswer
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()

🎯 Q1: What problem does async/await solve?

It allows code to wait for slow operations without blocking the thread.

🎯 Q2: What is Task?

Task represents an asynchronous operation that will complete later.

🎯 Q3: Difference between Task and Task<T>?

Task returns no value. Task<T> returns a value.

🎯 Q4: Why avoid async void?

Caller cannot await it and exceptions are harder to handle. Use async Task.

🎯 Q5: What is Task.WhenAll?

It waits for multiple tasks to finish and lets them run together.


🤖Use AI to Learn Faster
⚠️ Important for beginners: Do NOT use AI to write your code yet. Type every example yourself. Your brain learns by doing, not by reading AI output. Use AI only to explain and quiz you — not to code for you. Once you have strong fundamentals, AI becomes a powerful productivity tool for repetitive tasks.

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.

Next Article

Modern C# Features ->

nexcoding.in