C# uses Task
and async/await
to run code asynchronously (in the background).
πββοΈ Awaiting a Task
1
2
3
4
5
async Task RunAsync()
{
await Task.Delay(1000); // Wait 1 second
Console.WriteLine("Finished waiting!");
}
πΌ Awaiting Async Methods
You can await any method that returns a Task
or Task<T>
.
1
2
3
4
5
6
7
8
9
10
11
async Task<int> GetNumberAsync()
{
await Task.Delay(500);
return 42;
}
async Task UseNumberAsync()
{
int n = await GetNumberAsync();
Console.WriteLine(n);
}
π Why Await?
- Keeps your app responsive.
- Lets you write code that looks synchronous, but isnβt.
π‘ Try It!
Write a method that fetches data asynchronously (simulate with Task.Delay
), then prints the result.
1
2
3
4
5
async Task<string> FetchDataAsync()
{
await Task.Delay(1000);
return "Data loaded";
}
Next: Handling async errors!