9

Async Await Mastery: Handling Exceptions Like a Pro in C# 🚀

 2 months ago
source link: https://medium.com/@kmorpex/async-await-mastery-handling-exceptions-like-a-pro-in-c-300a45b7cdc3
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Async Await Mastery: Handling Exceptions Like a Pro in C# 🚀

3 min readMay 18, 2024
1*qjEDWLUl-Mh3rlWQmxUFoA.png

Hey, devs! 👋 In this article, we’re going to talk about some of the common mistakes people make when using async/await in C#. They might not be mistakes you see every day, but they’re important to know about. Let’s get started!

Introduction

Today, we’re going to talk about how to deal with exceptions when using the Task.WhenAll method. This is something that’s often done wrong in a lot of apps. Let’s say you have a bunch of dishes that need to be prepared at the same time. Here’s an example:

var pastaTask = CookDishAsync("Pasta", 10); // 10 minutes
var cakeTask = CookDishAsync("Cake", 30); // 30 minutes

await Task.WhenAll(pastaTask, cakeTask);

In this scenario, we’ll be cooking pasta and making a cake at the same time. With any luck, we should be able to get both things done in time.

The Problem

But, what happens when something goes wrong with one or both tasks? Let’s see.

var pastaTask = CookDishAsync("Pasta", 10); // Throws exception after 10 minutes
var cakeTask = CookDishAsync("Cake", 30); // Throws exception after 30 minutes

await Task.WhenAll(pastaTask, cakeTask);

When you run this code, it only throws the first error, not a bunch of them. That can be confusing and confusing, like if there were multiple problems in the kitchen, but you only noticed the first one.

Handling Exceptions Correctly

To handle this properly, you need to wrap the Task.WhenAll call in a try-catch block and then handle each exception individually.

var pastaTask = CookDishAsync("Pasta", 10);
var cakeTask = CookDishAsync("Cake", 30);

try
{
await Task.WhenAll(pastaTask, cakeTask);
}
catch (Exception ex)
{
Console.WriteLine($"Exception caught: {ex.Message}");
}

Using a Cancellation Token

Sometimes, you might have to cancel a task or two, like if the oven breaks and you can’t bake the cake. Let’s talk about how to deal with that using a cancellation token.

var cts = new CancellationTokenSource();

var pastaTask = CookDishAsync("Pasta", 10, cts.Token);
var cakeTask = CookDishAsync("Cake", 30, cts.Token);

try
{
// Cancel the baking task after 15 minutes (simulate oven failure)
cts.CancelAfter(TimeSpan.FromMinutes(15));

await Task.WhenAll(pastaTask, cakeTask);
}
catch (Exception ex)
{
Console.WriteLine($"Exception caught: {ex.Message}");
if (ex is OperationCanceledException)
{
Console.WriteLine("One or more tasks were canceled.");
}
}

In this example, we create CancellationTokenSource and pass the token to each task. We simulate an oven failure by canceling the tasks after 15 minutes.

Conclusion

By understanding how Task.WhenAll deals with exceptions and implementing thorough error handling, you can make sure your async code is strong and reliable. It’s not enough to just catch exceptions — you need to inspect and handle them properly to avoid major problems in your app, just like you wouldn’t want to ignore multiple kitchen accidents.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK