Ad Code

✨🎆 Codex 1.0 PLACEMENT READY PROGRAM! 🎆✨

Get 75% Discount Early bird offer CLICK to JOIN CodeX 1.0 click

Async | Await in C#

 In C#, async and await are keywords used to write asynchronous, non-blocking code in a clean and readable way. They make it easier to run tasks in the background (like calling APIs, reading files, querying a database) without freezing the main thread or UI.


1. What is async?

async is a modifier you apply to a method.

It tells the compiler:

“This method contains asynchronous operations and may use await.”

Example:

public async Task LoadDataAsync() { // asynchronous code will go here }

Key points:

  • An async method must return:

    • Task

    • Task<T>

    • or void (only for event handlers)

  • An async method can contain zero or more await keywords`.


2. What is await?

await is used inside an async method to pause execution until the awaited task finishes — without blocking the thread.

Example:

var result = await GetDataFromServerAsync();

What happens behind the scenes:

  • The method pauses at await

  • Control returns to the caller

  • Thread is free to do other work (UI stays responsive)

  • When the task finishes, method continues from that line


✅ Example: Without async/await (Blocking)

public string GetData() { Thread.Sleep(3000); // blocks for 3 seconds return "Data Loaded"; }

This freezes your UI or blocks the thread.


✅ Example: With async/await (Non-blocking)

public async Task<string> GetDataAsync() { await Task.Delay(3000); // non-blocking wait return "Data Loaded"; }

UI remains responsive.


✅ Real Example: Calling an API asynchronously

public async Task<string> GetWeatherAsync() { HttpClient client = new HttpClient(); var result = await client.GetStringAsync("https://api.weather.com"); return result; }
  • GetStringAsync runs in background

  • await waits without blocking

  • Easy to read and write


✅ Why async/await is useful?

✅ No UI freezing
✅ Better performance
✅ Efficient thread usage
✅ Clean and readable code
✅ Helps handle large workloads (API calls, file I/O, DB queries)




Post a Comment

0 Comments