async / await Basics
async and await let a program start a slow job, like waiting for a download, and do other things while it waits. It is like putting bread in the toaster and pouring juice instead of just staring.
In this page:
Syntax
static async Task<ReturnType> MethodNameAsync()
{
await SomeAsyncOperation(); // pauses without blocking the thread
return value;
}
ReturnType result = await MethodNameAsync();
async / await Basics
async marks a method as asynchronous, allowing it to use await to pause execution at a slow operation without blocking the calling thread.
Control returns to the caller while the awaited operation runs, then resumes the method when it completes. This keeps applications responsive during I/O-bound work like network or file access.
Note:
An
async method should return Task or Task<T> (or void only for event handlers), never block synchronously inside it.Example: async / await Basics
using System;
using System.Threading.Tasks;
class Program
{
static async Task<int> ComputeAsync()
{
await Task.Delay(100);
return 42;
}
static async Task Main(string[] args)
{
Console.WriteLine("Starting...");
int result = await ComputeAsync();
Console.WriteLine($"Result: {result}");
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
.Resultor.Wait()on a task in UI code, which can deadlock. - Forgetting
await, so the method continues before the task finishes. - Writing an
async voidmethod, which cannot be awaited and hides exceptions.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: