Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
Ravi Vishwakarma
12-Jun-2025The
async
andawait
pattern in C# is a language feature used to write asynchronous, non-blocking code in a clean, readable way.Instead of using callbacks or threads manually, you can write asynchronous code as if it were synchronous, while still freeing up threads to do other work (like serving more web requests).
Basic Concept
async
keyword: Marks a method as asynchronous.await
keyword: Tells the compiler to pause execution until the awaited task completes.Behind the scenes, the method gets "split" into parts that run before and after the
await
. The thread is returned to the pool while waiting.Components of the Pattern
async
Task
,Task<T>
, orValueTask<T>
await
Task
/Task<T>
Rules to Remember
await
inside a method marked withasync
.async
method must return:Task
(if it returns nothing),Task<T>
(if it returns a value),void
(only for event handlers).await
only works withTask
,Task<T>
,ValueTask
, orcustom awaitables
.Example: Asynchronous Delay
This method does not block the thread during the delay.
When Should You Use
async
/await
?Use it when:
Don’t use it when:
Task.Run()
without a good reasonawait
inside — this will show a compiler warningBad Example
Better:
Rule of Thumb