Correcting Common Async/Await Mistakes in .NET 8 - Brandon Minnick - NDC Porto 2023

Correct common mistakes in asynchronous programming in .NET 8 with expert tips on thread creation, cancellation, exceptions, and more. Learn best practices to improve performance and reliability in your .NET applications.

Key takeaways
  • The async keyword adds about 100 bytes and can lead to unnecessary thread creation.
  • The await keyword can be used to avoid unnecessary thread creation by allowing the thread to be reused.
  • Avoid using async void as it can lead to exceptions being swallowed and not propagated to the calling thread.
  • Use configure await false to avoid thread reuse and ensure that the calling thread is reused.
  • Use a cancellation token to cancel a task that is running in the background.
  • Use yield return to allow a method to return partial results instead of waiting for the entire method to complete.
  • Avoid using return await as it can lead to unnecessary thread creation.
  • Use try-catch block to handle exceptions and ensure that the task is cancelled if an exception is thrown.
  • Use a ValueTask to improve performance by avoiding unnecessary thread creation.
  • Use IAsyncEnumerable to allow a method to return a sequence of values instead of a single value.
  • Avoid using async in the constructor as it can lead to issues with the synchronization context.
  • Use configure await false in the constructor to ensure that the calling thread is reused.
  • Use IProgress<T> to report progress and handle exceptions in a background task.
  • Avoid using async in a using block as it can lead to issues with the synchronization context.