Async Best Practices

Write safe and efficient async code

Posted by Rodrigo Castro on December 29, 2024

Async is powerful, but there are some rules for writing safe, efficient code.

✅ Do

  • Use async and await for slow operations (file/network).
  • Always await async 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 .Result or .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!