DEV Community

VzlDev
VzlDev

Posted on

Mastering Async and Await in C#

Understanding the Async and Await Keywords

The async and await keywords are essential tools in C# for asynchronous programming. They streamline the creation of non-blocking code, enhancing readability and maintainability.

Async Keyword

The async keyword is used to mark a method as asynchronous, indicating that the method can perform a non-blocking operation

Await Keyword

The await keyword is used inside of an async method to temporarily suspend its execution and yield control back to the calling method until the awaited task is completed. This allows other tasks to continue executing in the meantime.

Example

Imagine you're a chef in a kitchen. Instead of waiting for each ingredient to be ready before moving on, you can do multiple tasks at the same time to improve the time of preparing a meal.

Synchronous Code

In a synchronous approach, each task waits for the previous one to complete before starting the next. Here’s an example:

static void Main(string[] args)
{
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();

    PrepareMeal();

    stopwatch.Stop();
    TimeSpan elapsed = stopwatch.Elapsed;
    Console.WriteLine($"Elapsed Time (Seconds): {elapsed.TotalSeconds} s");
    Console.ReadLine();
}

private static void PrepareMeal()
{
    Console.WriteLine("Preparing meal");
    CutVegetables();
    BoilWater();   
    CookVegetables();
}

private static void BoilWater()
{
    Console.WriteLine("Boiling water");
    Task.Delay(3000).Wait();
    Console.WriteLine("Water is boiling!");
}

private static void CutVegetables()
{
    Console.WriteLine("Cutting vegetables");
    Task.Delay(3000).Wait();
    Console.WriteLine("Vegetables are cut!");
}

private static void CookVegetables()
{
    Console.WriteLine("Put vegetables on boiling water");
    Task.Delay(5000).Wait();
    Console.WriteLine("Meal Done!");
}

Enter fullscreen mode Exit fullscreen mode

The output of the preparation of this meal will be:

Preparing meal
Boiling water
Water is boiling!
Cutting vegetables
Vegetables are cut!
Put vegetables on boiling water
Meal Done!
Final time - 11.03 seconds

Enter fullscreen mode Exit fullscreen mode

In this example, each task must finish before the next one starts, leading to a longer overall completion time.

Asynchronous Code

Using async and await allows tasks to overlap, enhancing efficiency. Here’s the asynchronous version:

static async Task Main(string[] args)
{
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();

    await PrepareMealAsynchronously();

    stopwatch.Stop();
    TimeSpan elapsed = stopwatch.Elapsed;
    Console.WriteLine($"Elapsed Time (Seconds): {elapsed.TotalSeconds} s");
    Console.ReadLine();
}

private static async Task PrepareMealAsynchronously()
{
    Console.WriteLine("Preparing meal asynchronously");

    Task boilWaterTask = BoilWaterAsynchronously();
    Task cutVegetablesTask = CutVegetablesAsynchronously();

    await Task.WhenAll(boilWaterTask, cutVegetablesTask);

    await CookVegetablesAsynchronously();
}

private static async Task BoilWaterAsynchronously()
{
    Console.WriteLine("Boiling water");
    await Task.Delay(3000);
    Console.WriteLine("Water is boiling!");
}

private static async Task CutVegetablesAsynchronously()
{
    Console.WriteLine("Cutting vegetables");
    await Task.Delay(3000);
    Console.WriteLine("Vegetables are cut!");
}

private static async Task CookVegetablesAsynchronously()
{
    Console.WriteLine("Put vegetables on boiling water");
    await Task.Delay(5000);
    Console.WriteLine("Meal done!");
}

Enter fullscreen mode Exit fullscreen mode

The output of the preparation of this meal will be:

Preparing meal asynchronously
Boiling water
Cutting vegetables
Water is boiling!
Vegetables are cut!
Put vegetables on boiling water
Done cooking!
Final time - 8.01 seconds
Enter fullscreen mode Exit fullscreen mode

In this asynchronous approach, tasks like boiling water and chopping vegetables can proceed simultaneously, reducing the overall cooking time.

Benefits of Asynchronous Approach

Asynchronous cooking, or programming, allows tasks to be executed concurrently, making better use of time and resources. This results in faster completion of tasks, as the system can handle multiple operations at once. For instance, while waiting for the water to boil, you can simultaneously chop vegetables, significantly cutting down the total time needed.

And that's it guys, a simple explanation and example of asynchronous calls with .net.
There's still plenty more to learn, I hope you liked it, stay tuned for more!

Top comments (0)