Skip to content

Async / Await

Async Functions

Mark a function async to make it asynchronous. The async keyword appears before the return type:

async int FetchValue()
{
int data = await LoadData();
return data;
}

Awaiting Results

Use await inside an async function to wait for an asynchronous operation to complete:

async void Main()
{
int value = await FetchValue();
Console.WriteLine($"{value}");
}

Async with Parameters

async int AddAsync(int a, int b)
{
return a + b;
}
async int ComputeAsync(int x)
{
int result = x * 2;
return result + 5;
}

Async with Control Flow

async int ConditionalAsync(int x)
{
if (x > 10)
{
return x * 2;
}
return x;
}

Threads

Create OS threads directly with Thread:

void Work()
{
Console.WriteLine("Running on background thread");
}
Thread t = Thread(Work);
t.Start();
t.Join();

Thread with Closures

Thread t = Thread(() =>
{
Console.WriteLine("Background work");
});
t.Start();
t.Join();