Async is powerful, but there are some rules for writing safe, efficient code.
✅ Do
- Use
asyncandawaitfor slow operations (file/network). - Always
awaitasync methods, don’t ignore the result. - Use
ConfigureAwait(false)in libraries where context doesn’t matter.
🚫 Don’t
- Don’t use
async void(except for event handlers). - Don’t block with
.Resultor.Wait()this can deadlock your app. - Don’t start an async method and forget to await or handle its Task.
📝 Example
1
2
3
4
5
async Task<int> GetDataAsync()
{
await Task.Delay(1000);
return 42;
}
Good:
1
int n = await GetDataAsync();
Bad:
1
int n = GetDataAsync().Result; // Don’t do this!
💡 Try It!
Write an async method and always remember to await it!
Next: Unit testing basics!