Lädt...


🔧 Mastering Async and Await in C#


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

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!");
}

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

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!");
}

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

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!

...

🔧 Is async/await a good idea? 🤔 async/await vs promises


📈 66.23 Punkte
🔧 Programmierung

🔧 Mastering Async/Await: Simplifying JavaScript's Async Operations


📈 58.06 Punkte
🔧 Programmierung

🔧 Async Made Easy: A Deep Dive into JavaScript Callbacks, Promises, and Async/Await


📈 49.98 Punkte
🔧 Programmierung

🔧 Async Made Easy: A Deep Dive into JavaScript Callbacks, Promises, and Async/Await


📈 49.98 Punkte
🔧 Programmierung

🔧 Async… oh, wait (Introduction into Async/Await)


📈 48.31 Punkte
🔧 Programmierung

🔧 Mastering Async and Await in C#


📈 44.54 Punkte
🔧 Programmierung

🔧 Mastering Asynchronous JavaScript: A Guide to async/await and Promises ⌛️


📈 44.54 Punkte
🔧 Programmierung

🔧 Mastering Asynchronous JavaScript: Promises, Async/Await, and Callbacks


📈 44.54 Punkte
🔧 Programmierung

🔧 Mastering Asynchronous JavaScript: A Guide to async/await and Promises ⌛️


📈 44.54 Punkte
🔧 Programmierung

🔧 Mastering Asynchronous Programming in C#: A Deep Dive into Async/Await


📈 42.87 Punkte
🔧 Programmierung

🔧 Mastering Async Await in JavaScript for Asynchronous Programming


📈 42.87 Punkte
🔧 Programmierung

🔧 Mastering Async/Await in JavaScript Like a Pro!


📈 42.87 Punkte
🔧 Programmierung

🔧 Mastering Async/Await in TypeScript: A Comprehensive Guide


📈 42.87 Punkte
🔧 Programmierung

🔧 Using Promises and Async/Await in JavaScript


📈 34.78 Punkte
🔧 Programmierung

🔧 Understand the Asynchronous JavaScript: Callbacks, Promises, and Async/Await


📈 34.78 Punkte
🔧 Programmierung

🔧 Callbacks, Promises, and Async-Await


📈 34.78 Punkte
🔧 Programmierung

🔧 Understanding Asynchronous Operations and Using async/await in JavaScript


📈 34.78 Punkte
🔧 Programmierung

🔧 Asynchronous JavaScript: Promises, Async/Await, and Callbacks


📈 34.78 Punkte
🔧 Programmierung

🔧 Async / Await and Asyncio In Python


📈 34.78 Punkte
🔧 Programmierung

🔧 How Asynchronous Programming Works in Rust – Futures and Async/Await Explained with Examples


📈 34.78 Punkte
🔧 Programmierung

🔧 Understanding Asynchronous JavaScript: Callbacks, Promises, and Async/Await


📈 34.78 Punkte
🔧 Programmierung

🔧 Understanding closures, promises, and async/await


📈 34.78 Punkte
🔧 Programmierung

🔧 Master Async/Await in JavaScript: Tips and Tricks for Pros


📈 34.78 Punkte
🔧 Programmierung

🔧 Asynchronous JavaScript: Callbacks, Promises, and Async/Await


📈 34.78 Punkte
🔧 Programmierung

🔧 Async/await and SwiftUI


📈 34.78 Punkte
🔧 Programmierung

🔧 Exploring Asynchronous JavaScript: Callbacks, Promises, and Async/Await


📈 34.78 Punkte
🔧 Programmierung

🔧 Promices and Async Await


📈 34.78 Punkte
🔧 Programmierung

🔧 A comprehensive guide to Promises, Async, and Await in JavaScript


📈 34.78 Punkte
🔧 Programmierung

🔧 Async and Await in JavaScript: A Comprehensive Guide


📈 34.78 Punkte
🔧 Programmierung

🐧 How to Build a Basic CLI App using Node.js readline and Async/Await


📈 34.78 Punkte
🐧 Linux Tipps

🔧 A Beginner’s Guide to JavaScript async/await, with Examples


📈 33.12 Punkte
🔧 Programmierung

🎥 Async/Await: Close collaboration across non-overlapping time zones


📈 33.12 Punkte
🎥 Video | Youtube

🔧 The Long Road to Async/Await in JavaScript


📈 33.12 Punkte
🔧 Programmierung

🔧 24 Essential Async/Await Best Practices for Basic to Advanced C# Developers


📈 33.12 Punkte
🔧 Programmierung

matomo