Async Await - potatoscript/csharp GitHub Wiki

πŸ₯” Asynchronous Programming in C# πŸ₯”


🎯 What is Asynchronous Programming?

Imagine you’re making French fries 🍟 from potatoes. You:

  • πŸ₯” Peel the potatoes.
  • πŸ”ͺ Cut them into slices.
  • 🌊 Wash the slices.
  • 🍳 Fry them until crispy.

If you did this step by step, waiting for each task to finish before starting the next, it would take forever! ⏳ But if you ask your potato buddy to help wash the slices while you cut the rest, things go much faster! ⚑πŸ₯”

βœ… Synchronous Code: Doing everything one by one (waiting for each task to finish). βœ… Asynchronous Code: Doing multiple tasks at the same time (without waiting).


⚑ Why Use Asynchronous Programming?

Without asynchronous programming:

  • 🐒 Everything happens one step at a time.
  • ⏰ You spend a lot of time waiting.

With asynchronous programming:

  • πŸš€ Multiple tasks happen simultaneously.
  • πŸŽ‰ Your program runs much faster and is more efficient.

🧠 How Asynchronous Programming Works?

In C#, asynchronous programming is done using:

  • async – Tells the method that it contains asynchronous operations.
  • await – Pauses and waits for an asynchronous task to finish before moving on.

πŸ₯” Basic Syntax of Async and Await

async Task FryPotatoesAsync()
{
    Console.WriteLine("🍽️ Preparing potatoes...");
    await Task.Delay(3000);  // Simulate frying for 3 seconds
    Console.WriteLine("🍟 French fries are ready!");
}

βœ… Explanation:

  • async – Marks the method as asynchronous.
  • Task.Delay(3000) – Wait for 3 seconds.
  • await – Waits for the frying task to finish before continuing.

πŸŽ‰ Synchronous vs. Asynchronous Example

🐒 Synchronous Version

using System;

class Program
{
    static void Main()
    {
        PeelPotatoes();
        CutPotatoes();
        FryPotatoes();
        Console.WriteLine("🍽️ All tasks finished!");
    }

    static void PeelPotatoes()
    {
        Console.WriteLine("πŸ₯” Peeling potatoes...");
        System.Threading.Thread.Sleep(2000);  // 2 seconds
        Console.WriteLine("βœ… Done peeling.");
    }

    static void CutPotatoes()
    {
        Console.WriteLine("πŸ”ͺ Cutting potatoes...");
        System.Threading.Thread.Sleep(2000);  // 2 seconds
        Console.WriteLine("βœ… Done cutting.");
    }

    static void FryPotatoes()
    {
        Console.WriteLine("🍳 Frying potatoes...");
        System.Threading.Thread.Sleep(3000);  // 3 seconds
        Console.WriteLine("βœ… Done frying.");
    }
}

🎁 Output:

πŸ₯” Peeling potatoes...
βœ… Done peeling.
πŸ”ͺ Cutting potatoes...
βœ… Done cutting.
🍳 Frying potatoes...
βœ… Done frying.
🍽️ All tasks finished!

βœ… Problem: Tasks take a lot of time because each one waits for the previous to finish.


πŸš€ Asynchronous Version

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Task peelTask = PeelPotatoesAsync();
        Task cutTask = CutPotatoesAsync();
        Task fryTask = FryPotatoesAsync();

        // Wait for all tasks to finish
        await Task.WhenAll(peelTask, cutTask, fryTask);

        Console.WriteLine("🍽️ All tasks finished!");
    }

    static async Task PeelPotatoesAsync()
    {
        Console.WriteLine("πŸ₯” Peeling potatoes...");
        await Task.Delay(2000);  // 2 seconds
        Console.WriteLine("βœ… Done peeling.");
    }

    static async Task CutPotatoesAsync()
    {
        Console.WriteLine("πŸ”ͺ Cutting potatoes...");
        await Task.Delay(2000);  // 2 seconds
        Console.WriteLine("βœ… Done cutting.");
    }

    static async Task FryPotatoesAsync()
    {
        Console.WriteLine("🍳 Frying potatoes...");
        await Task.Delay(3000);  // 3 seconds
        Console.WriteLine("βœ… Done frying.");
    }
}

🎁 Output:

πŸ₯” Peeling potatoes...
πŸ”ͺ Cutting potatoes...
🍳 Frying potatoes...
βœ… Done peeling.
βœ… Done cutting.
βœ… Done frying.
🍽️ All tasks finished!

βœ… Benefit: Tasks happen simultaneously! You don’t wait for one to finish before starting the next.


πŸ₯” Understanding async and await

🎯 Key Points:

  1. async – Marks a method as asynchronous.
  2. await – Waits for an asynchronous task to finish.
  3. Task – Represents an asynchronous operation.
  4. Task.WhenAll() – Waits for multiple tasks to complete.

πŸ₯” Return Types in Asynchronous Methods

1️⃣ Return Nothing (void)

async void FryPotatoesAsync()
{
    await Task.Delay(3000);
    Console.WriteLine("🍟 French fries ready!");
}

2️⃣ Return a Task

async Task ServeDinnerAsync()
{
    await Task.Delay(2000);
    Console.WriteLine("🍽️ Dinner is served!");
}

3️⃣ Return a Task with Result

async Task<int> CountPotatoesAsync()
{
    await Task.Delay(1000);
    return 5;  // 5 potatoes counted
}

πŸ₯” Handling Errors in Asynchronous Code

Just like sometimes potatoes burn πŸ”₯ if you leave them too long, errors can happen in async code.

🎯 Try-Catch with Async

async Task FryPotatoesSafelyAsync()
{
    try
    {
        Console.WriteLine("🍳 Starting to fry...");
        await Task.Delay(2000);
        throw new Exception("πŸ”₯ Oil is too hot!");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"⚠️ Error: {ex.Message}");
    }
    finally
    {
        Console.WriteLine("🧹 Cleaning up the kitchen...");
    }
}

βœ… Explanation:

  • try – Run the frying code.
  • catch – Catch any errors.
  • finally – Always clean up the kitchen.

🎁 Output:

🍳 Starting to fry...
⚠️ Error: πŸ”₯ Oil is too hot!
🧹 Cleaning up the kitchen...

πŸ₯” Real-Life Example: Fetching Data Asynchronously

Imagine you are ordering potatoes online πŸ₯”πŸ“¦. It takes some time for the server to respond, and you don’t want to wait forever.

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("πŸ“¦ Placing potato order...");
        string response = await FetchPotatoesAsync();
        Console.WriteLine(response);
    }

    static async Task<string> FetchPotatoesAsync()
    {
        using HttpClient client = new HttpClient();
        string url = "https://api.potatoscript.com/getpotatoes";
        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            return "πŸ₯” Potatoes have arrived!";
        }
        else
        {
            return "❌ No potatoes found!";
        }
    }
}

βœ… Explanation:

  • HttpClient.GetAsync() – Fetch data from a server asynchronously.
  • await – Wait for the server to respond.

🎁 Output:

πŸ“¦ Placing potato order...
πŸ₯” Potatoes have arrived!

πŸ₯” Summary of Asynchronous Programming

🌟 Feature πŸ“ Description
⏳ async/await Run tasks asynchronously without blocking.
πŸš€ Faster Execution Allows multiple operations to happen at once.
πŸ› οΈ Task Handling Wait for multiple tasks using Task.WhenAll().
⚑ Error Handling Use try-catch to handle async errors.
⚠️ **GitHub.com Fallback** ⚠️