Async Await - potatoscript/csharp GitHub Wiki
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).
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.
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.
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.
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.");
}
}
π₯ 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.
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.");
}
}
π₯ 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.
-
async
β Marks a method as asynchronous. -
await
β Waits for an asynchronous task to finish. -
Task
β Represents an asynchronous operation. -
Task.WhenAll()
β Waits for multiple tasks to complete.
async void FryPotatoesAsync()
{
await Task.Delay(3000);
Console.WriteLine("π French fries ready!");
}
async Task ServeDinnerAsync()
{
await Task.Delay(2000);
Console.WriteLine("π½οΈ Dinner is served!");
}
async Task<int> CountPotatoesAsync()
{
await Task.Delay(1000);
return 5; // 5 potatoes counted
}
Just like sometimes potatoes burn π₯ if you leave them too long, errors can happen in async code.
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.
π³ Starting to fry...
β οΈ Error: π₯ Oil is too hot!
π§Ή Cleaning up the kitchen...
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.
π¦ Placing potato order...
π₯ Potatoes have arrived!
π 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. |