Async programming lets your program do more than one thing at once: great for web requests, file I/O, and keeping apps fast.
🚦 Why Use Async?
- Don’t block the program while waiting for slow things (like files or the internet).
- Keeps apps smooth and responsive.
✨ The Basics: async
and await
1
2
3
4
5
async Task MyMethodAsync()
{
await Task.Delay(1000);
Console.WriteLine("Done waiting!");
}
async
marks a method as asynchronous.await
pauses until the operation is done, but doesn’t freeze your app.
📥 Async Main Example
1
2
3
4
static async Task Main(string[] args)
{
await MyMethodAsync();
}
đź’ˇ Try It!
Write an async method that prints “Hello” after 2 seconds.
1
2
3
4
5
async Task SayHelloAsync()
{
await Task.Delay(2000);
Console.WriteLine("Hello");
}
Next: Awaiting tasks and methods!