What is async await in C#: Simple Explanation and Example
async and await in C# are keywords that let you write code that runs tasks without blocking the program. async marks a method to run asynchronously, and await pauses the method until the task finishes, keeping the app responsive.How It Works
Imagine you are cooking dinner and waiting for water to boil. Instead of just standing there doing nothing, you start chopping vegetables. In programming, async and await work like this: async marks a method that can pause and resume, and await tells the program to wait for a task to finish without stopping everything else.
This means your program can do other things while waiting, like responding to user clicks or loading data. When the awaited task is done, the program continues from where it paused. This helps keep apps smooth and fast.
Example
This example shows a simple async method that waits for 2 seconds before printing a message. The main method continues running without waiting.
using System; using System.Threading.Tasks; class Program { static async Task Main() { Console.WriteLine("Start"); await WaitAndPrintAsync(); Console.WriteLine("End"); } static async Task WaitAndPrintAsync() { await Task.Delay(2000); // Wait 2 seconds Console.WriteLine("Waited 2 seconds"); } }
When to Use
Use async and await when your program needs to do long tasks like reading files, calling web services, or waiting for user input without freezing the screen. For example, in apps with buttons and menus, async code keeps the interface smooth while loading data.
This is especially useful in desktop apps, web servers, and mobile apps where responsiveness matters a lot.
Key Points
- async marks a method that can run asynchronously.
- await pauses the method until the awaited task finishes.
- Async methods help keep programs responsive by not blocking the main thread.
- Use async/await for I/O operations, network calls, and long-running tasks.
- Async methods usually return
TaskorTask<T>.