0
0
C Sharp (C#)programming~5 mins

Async and await keywords in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Async and await help your program do many things at once without waiting. This makes your app faster and smoother.

When you want to download a file without freezing the app.
When you need to get data from the internet and still let the user click buttons.
When you want to read or write files without making the program stop.
When you want to run a long task but keep the app responsive.
When you want to wait for a task to finish without blocking other work.
Syntax
C Sharp (C#)
async Task MethodName()
{
    await SomeAsyncOperation();
}

async marks a method that can run tasks without blocking.

await waits for the task to finish but lets other work happen meanwhile.

Examples
This method waits 1 second without blocking, then prints a message.
C Sharp (C#)
async Task DownloadFileAsync()
{
    await Task.Delay(1000); // Simulate waiting
    Console.WriteLine("File downloaded");
}
This async method waits half a second and then returns a number.
C Sharp (C#)
async Task<int> GetNumberAsync()
{
    await Task.Delay(500);
    return 42;
}
Here we wait for GetNumberAsync to finish and then print the result.
C Sharp (C#)
async Task UseAsync()
{
    int result = await GetNumberAsync();
    Console.WriteLine($"Result is {result}");
}
Sample Program

This program shows how async and await let the program wait 2 seconds without freezing. It prints messages before and after the wait.

C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("Start downloading...");
        await DownloadFileAsync();
        Console.WriteLine("Download complete.");
    }

    static async Task DownloadFileAsync()
    {
        await Task.Delay(2000); // Wait 2 seconds
        Console.WriteLine("File downloaded");
    }
}
OutputSuccess
Important Notes

Async methods usually return Task or Task<T> to represent ongoing work.

You can only use await inside methods marked async.

Using async and await keeps your app responsive and easy to read.

Summary

Use async to mark methods that run tasks without blocking.

Use await to wait for tasks to finish while letting other work continue.

Async and await help keep apps fast and responsive.