C# — Async and Await — Best Practices

Robin Ding
1 min readSep 7, 2021
  1. How does it work?
  2. Best Practices
  3. IO Based vs CPU Based
  4. SynchronizationContext & TaskScheduler
  5. Deadlock
  6. ConfigureAwait(false) & FodyWeavers
  7. How to call async method syncly & How to call sync method asyncly?
  8. Comparison (Console, WinForm, ASP.NET MVC, ASP.NET WebAPI, ASP.NET Core)

Summary

Summary of Asynchronous Programming Guidelines

Name Description Exceptions Avoid async void Prefer async Task methods over async void methods Event handlers Async all the way Don’t mix blocking and async code Console main method Configure context Use ConfigureAwait(false) when you can Methods that require con­text

The “Async Way” of Doing Things — Don’t block async

To Do This … Instead of This … Use This Retrieve the result of a background task Task.Wait or Task.Result await Wait for any task to complete Task.WaitAny await Task.WhenAny Retrieve the results of multiple tasks Task.WaitAll await Task.WhenAll Wait a period of time Thread.Sleep await Task.Delay

Solutions to Common Async Problems

Problem Solution Create a task to execute code Task.Run or TaskFactory.StartNew (not the Task constructor or Task.Start) Create a task wrapper for an operation or event TaskFactory.FromAsync or TaskCompletionSource<T> Support cancellation CancellationTokenSource and CancellationToken Report progress IProgress<T> and Progress<T> Handle streams of data TPL Dataflow or Reactive Extensions Synchronize access to a shared resource SemaphoreSlim Asynchronously initialize a resource AsyncLazy<T> Async-ready producer/consumer structures TPL Dataflow or AsyncCollection<T>

References

  1. https://docs.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming
  2. https://devblogs.microsoft.com/dotnet/configureawait-faq/
  3. https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
  4. https://blog.stephencleary.com/2012/02/async-and-await.html
  5. https://docs.microsoft.com/en-us/dotnet/csharp/async
  6. https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap
  7. https://docs.microsoft.com/en-us/dotnet/standard/async-in-depth
  8. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/task-asynchronous-programming-model

--

--