Handling Exceptions in Async Code - C#

When working with asynchronous code in C#, it's important to be aware of how exceptions are handled. Asynchronous methods can throw exceptions just like synchronous methods, but the way that these exceptions are handled is slightly different. In this post, we’re going to explore the different ways you can handle exceptions that occur within asynchronous methods.

First, let's take a look at a simple example of an asynchronous method that throws an exception. The following code defines a method called "DoWorkAsync" that simulates an exception being thrown:

public async Task DoWorkAsync() 
{ 
  throw new Exception("An exception occurred."); 
}

When an exception is thrown in an asynchronous method, it is wrapped in an AggregateException. This is because an asynchronous method can return multiple exceptions if it is waiting on multiple tasks. To handle this exception, you can use the try-catch block like this:

try 
{ 
  await DoWorkAsync(); 
} 
catch (AggregateException ex) 
{ 
  Console.WriteLine(ex.InnerException.Message);
}

In this example, the catch block is catching the AggregateException and then using the InnerException property to access the original exception that was thrown.

Another way to handle exceptions in asynchronous methods is to use the await keyword with the Task.Wait() or Task.Result method. Both of them will unwrap the aggregate exception and throw the original exception.

await DoWorkAsync().Wait();

or

await DoWorkAsync().Result;

It's important to note that Task.Wait() and Task.Result will block the current thread until the task is completed, so it's not recommended to use them in a high-performance scenario.

Another option is to use await with the Task.ConfigureAwait(false) method. This method is used to tell the runtime that it's safe to continue the execution of the task on a different thread context, it's useful when the method is called

Previous
Previous

What’s new in .NET 7.0

Next
Next

Understanding Async in C#