Best practices in .Net asynchronous programming

When working with asynchronous code in your applications, follow the recommended best practices to avoid potential pitfalls

Async void

Async void

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<T> 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<T>, 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.

This article is published as part of the IDG Contributor Network. Want to Join?

To comment on this article and other InfoWorld content, visit InfoWorld's LinkedIn page, Facebook page and Twitter stream.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.