The async/awaitpattern in C# is used to write
asynchronous, non-blocking code in a way that is easy to read and maintain — like synchronous code, but without blocking threads.
It’s built on top of the Task or Task<T> type and enables you to perform
I/O-bound or CPU-bound operations without freezing the app.
Basic Syntax
public async Task<string> GetDataAsync()
{
// This does not block the calling thread
await Task.Delay(2000);
return "Hello, async!";
}
async: marks a method as asynchronous.
await: pauses execution until the awaited task completes.
The return type is usually Task, Task<T>, or
void (for event handlers only).
Example with HttpClient
public async Task<string> FetchWebsiteAsync()
{
using (HttpClient client = new HttpClient())
{
string result = await client.GetStringAsync("https://example.com");
return result;
}
}
When Should You Use async/await?
Use Case
Use async/await?
Notes
I/O-bound operations
Yes
HTTP calls, file I/O, DB queries, etc.
CPU-bound operations
Prefer Task.Run
Don't use async to parallelize loops or math-heavy code.
UI applications (WPF, WinForms)
Yes
Prevents freezing the UI thread.
ASP.NET/Web API
Yes
Frees up threads for other requests.
Library/helper methods
Yes
Mark them async to compose cleanly with other async methods.
Common Mistakes
Mistake
Explanation
Using .Result or .Wait() on async methods
Can cause deadlocks, especially in UI apps
async void (except event handlers)
Not awaitable, can't catch exceptions
Mixing blocking and async code
Breaks scalability, introduces bugs
Composing Async Calls
public async Task<string> GetUserDataAsync()
{
var profile = await GetProfileAsync();
var settings = await GetSettingsAsync(profile.Id);
return $"{profile.Name} - {settings.Theme}";
}
Benefits of async/await
Non-blocking execution — improves scalability
Better performance — frees up threads during I/O
Easier to read — compared to callbacks or raw Task.ContinueWith()
Improves UI responsiveness — avoids freezing
Summary
Feature
Description
async
Marks a method as asynchronous
await
Asynchronously waits for a task to complete
Return type
Usually Task, Task<T>, or void (event only)
Use case
Ideal for I/O-bound operations (file, web, db)
Avoid for
CPU-heavy work unless combined with Task.Run
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Basic Syntax
async: marks a method as asynchronous.await: pauses execution until the awaited task completes.Task,Task<T>, orvoid(for event handlers only).Example with
HttpClientWhen Should You Use
async/await?async/await?Task.Runasyncto parallelize loops or math-heavy code.Common Mistakes
.Resultor.Wait()on async methodsasync void(except event handlers)Composing Async Calls
Benefits of
async/awaitTask.ContinueWith()Summary
asyncawaitTask,Task<T>, orvoid(event only)Task.Run