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

How async execution flows in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Async execution helps your program do many things at once without waiting. It keeps your app fast and smooth.

When you want to download files without freezing your app.
When you need to read data from a database and still let users click buttons.
When calling web services that take time to respond.
When you want to run background tasks without stopping the main work.
Syntax
C Sharp (C#)
async Task MethodNameAsync()
{
    await SomeAsyncOperation();
    // code here runs after await finishes
}

async marks a method that can run asynchronously.

await pauses the method until the awaited task finishes, but does not block the whole program.

Examples
This method waits 1 second asynchronously, then prints a message.
C Sharp (C#)
async Task DownloadFileAsync()
{
    await Task.Delay(1000); // simulates waiting
    Console.WriteLine("Download complete");
}
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;
}
Sample Program

This program shows how async lets the program continue working while waiting. It prints messages before and after the delay.

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

class Program
{
    static async Task Main()
    {
        Console.WriteLine("Start");
        Task task = PrintAfterDelayAsync();
        Console.WriteLine("Doing other work");
        await task;
        Console.WriteLine("End");
    }

    static async Task PrintAfterDelayAsync()
    {
        await Task.Delay(1000); // wait 1 second
        Console.WriteLine("Hello after delay");
    }
}
OutputSuccess
Important Notes

Async methods do not block the main thread, so your app stays responsive.

Use await to pause only the async method, not the whole program.

Async methods usually return Task or Task<T>.

Summary

Async lets your program do other things while waiting.

Use async and await keywords to write async code.

Async methods improve app speed and user experience.