When working with asynchronous code in your applications, follow the recommended best practices to avoid potential pitfalls Asynchronous programming enables you to perform resource-intensive I/O operations without having to block on the main or the executing thread of the application. Though beneficial and seemingly easy to implement, it comes with a lot of complexity and risks. The potential risks associated with async programming, particularly using asynchronous programming the wrong way by not following the recommended practices, include deadlocks, process crashes and even slow performance. You should also be proficient in writing, debugging async code. Avoid having void return type in async methods A method in C# is made an asynchronous method using the async keyword in the method signature. You can have one or more await keywords inside an async method. The await keyword is used to denote the suspension point. An async method in C# can have any one of these return types: Task, Task and void. The “await” keyword is used in an async method to inform the compiler that the method can have a suspension and resumption point. Note that when using the TPL, the equivalent of returning void in TPL is async Task. You should be aware that async void is and should only be used for async events. If you use it anywhere else, you would run into errors. In other words, an async method that has void as a return type is not recommended. because async methods that return void have different semantics when you are working with exceptions in your application. When an exception occurs in an async method that has a return type of Task or Task, the exception object is stored inside the Task object. On the contrary, if you have an async method with a return type of void, there is no Task object associated. Such exceptions are raised on the SynchronizationContext that was active at the time when the asynchronous method was called. In other words, you cannot handle exceptions raised within an async void method using exception handlers written inside the asynchronous method. Async methods that have a return type of void are also difficult to test due to this difference in error handling semantics. For your information, the SynchronizationContext class in the System.Threading namespace represents a synchronization context in .Net and helps you to queue a task onto another context. The following code listing illustrates this. You have two methods namely, Test and TestAsync and the latter throws an exception. public class AsyncDemo { public void Test() { try { TestAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } private async void TestAsync() { throw new Exception("This is an error message"); } } Here is how you can create an instance of the AsyncDemo class and invoke the Test method. static void Main(string[] args) { AsyncDemo obj = new AsyncDemo(); obj.Test(); Console.Read(); } The test method makes a call to the TestAsync method and the call is wrapped inside a try-catch block with the intent of handling the exception thrown inside the TestAsync method. However, the exception thrown inside the TestAsync method will never be caught, i.e., handled inside the caller method Test. Avoid mixing asynchronous and synchronous code You should never have a mix of synchronous and asynchronous code. It is a bad programming practice to block on async code by making calls to Task.Wait or Task.Result. I would recommend using async code end to end – it is the safest way to avoid errors from creeping in. You can avoid deadlocks by using .ConfigureAwait(continueOnCapturedContext: false) whenever you make a call to await. If you don’t use this, the async method would block at the point where await has been called. In this case you are just informing the awaiter not to capture the current context. I would say that it is a good practice to use .ConfigureAwait(false) unless you have a specific reason to not use it. I would discuss more on asynchronous programming in my future blog posts here. For more information on best practices in asynchronous programming, you can refer to Stephen Cleary’s great article at MSDN. Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos