Techiehook Techiehook
Updated date Sep 06, 2024
This post explains the concepts of asynchronous programming in C# using the async and await keywords.

Implementing Async and Await in C#

In C#, async and await are used to work with asynchronous programming, which allows you to perform time-consuming tasks (like network requests, file I/O, or database queries) without blocking the execution of your program. This is really useful for more responsive applications, especially in scenarios like desktop applications, web servers, and UI-based apps.

Concepts of async and await:

  1. async keyword:  It allows the method to run asynchronously and return a Task or Task<T>. The method will use the await keyword to signal where the asynchronous operation takes place.

  2. await keyword: Pauses the execution of the method until the awaited task completes. The method's execution continues once the awaited task is done, without blocking the calling thread.

Program:

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("Fetching data...");
        
        // Calling an async method and awaiting its result
        string result = await FetchDataAsync();
        
        Console.WriteLine($"Data fetched: {result}");
        
        Console.WriteLine("Processing complete.");
    }

    // Simulating a long-running task using Task.Delay
    public static async Task<string> FetchDataAsync()
    {
        // Below line (Task.Delay) simulate a 6-second delay to mimic a long-running task (e.g., network request)
        await Task.Delay(6000);
        
        return "Hello, TechieHook!";
    }
}

Output:

The program fetches the data asynchronously without blocking the main thread, and it displays the output once the task is completed after 3 seconds.

Fetching data...
(Data fetching happens for 6 seconds)
Data fetched: Hello, TechieHook!
Processing complete.

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!