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
:
-
async
keyword: It allows the method to run asynchronously and return aTask
orTask<T>
. The method will use theawait
keyword to signal where the asynchronous operation takes place. -
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.
Comments (0)