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
awaitkeywords`.
✅ 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.
Program obj = new Program();
String result = await obj.GetData();
Console.WriteLine(result);
✅ Real Example: Calling an API asynchronously
using System; using System.Net.Http; using System.Threading.Tasks; internal class Program { static async Task Main(string[] args) { Console.WriteLine("Fetching data..."); string data = await GetUserDataAsync(); Console.WriteLine("Response received:"); Console.WriteLine(data); Console.WriteLine("Program finished"); } static async Task<string> GetUserDataAsync() { using HttpClient client = new HttpClient(); // Public test API string url = "https://jsonplaceholder.typicode.com/users/1"; HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } }
-
GetStringAsyncruns in background -
awaitwaits 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)

0 Comments
POST Answer of Questions and ASK to Doubt