async
and await
make asynchronous programming straightforward in C#.
🏁 Declaring an Async Method
1
2
3
4
5
| public async Task<int> GetDataAsync()
{
await Task.Delay(1000); // Simulate async work
return 42;
}
|
⏩ Awaiting Tasks
- Use
await
to asynchronously wait for a Task
to complete.
- Control returns to the caller while the task runs.
1
2
| int result = await GetDataAsync();
Console.WriteLine(result);
|
🛑 Error Handling
- Use try/catch for exceptions in async methods.
1
2
3
4
5
6
7
8
| try
{
await DoSomethingAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
|
⚠️ Best Practices
- Never block on async code with
.Result
or .Wait()
.
- Use
ConfigureAwait(false)
in library code.
Next: Working with Task and parallel processing!