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.
✅ 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;
}
-
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