async and await in csharp

In c#, async and await keywords are used to perform the asynchronous operation without blocking the main thread.

Understanding Async and Await

Async/Await allows us to write asynchronous code more easily. It helps keep your application responsive, especially when dealing with I/O-bound operations like web requests or file access.

Async

It is used to mark a method as asynchronous, allowing it to perform non-blocking operations. This method can then return a Task or Task<TResult> object. It is particularly useful for GUI applications where we want to keep the interface responsive.

Await

Await is used within an async method to temporarily suspend its execution and return control to the calling method. This allows the program to continue with other tasks while waiting for the asynchronous operation to complete.

Key Concept of Async and Await

  1. Task-based Asynchronous Pattern (TAP): In C#, asynchronous methods typically return a Task or Task<T>, representing the ongoing work.
  2. async Modifier: We use the async keyword before a method declaration to indicate that it contains asynchronous operations.
  3. await Operator: This operator is used to pause the execution of the method until the awaited task completes, without blocking the thread.

Example

Here's a basic example of creating an async method:

csharp
public async Task<string> GetDataAsync() { // Simulate a delay (e.g., a web request) await Task.Delay(2000); return "Data retrieved!"; }

Calling an Async Method

To call an asynchronous method, you also use await:

csharp
public async Task ExecuteAsync() { string result = await GetDataAsync(); Console.WriteLine(result); }

Exception Handling

we can also handle exceptions in async methods using try-catch blocks:

csharp
public async Task<string> GetDataAsync() { try { await Task.Delay(2000); throw new Exception("Error occurred!"); } catch (Exception ex) { Console.WriteLine(ex.Message); return "Error handled."; } }

Benefits of Async/Await

  • Improved Performance: It allows multiple operations to run concurrently, improving application performance.
  • Simpler Code: Their code is easier to read and maintain compared to traditional asynchronous programming with callbacks.

Common Use Cases

  • I/O Operations: Reading from files, making web API calls.
  • Database Operations: Fetching or saving data without blocking the UI.
  • Long-running Tasks: Background processing while keeping the UI responsive. 

Example

Web API Call: here in this example, we are calling the web API asynchronously:

csharp
using System.Net.Http; public async Task<string> FetchDataFromApiAsync(string url) { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } }

Using async and await in C#, makes it easier to write non-blocking code, which increases application responsiveness. By understanding and applying the basic pattern, we can effectively manage asynchronous processing in your applications.

line

Copyrights © 2024 letsupdateskills All rights reserved