In c#, async and await keywords are used to perform the asynchronous operation without blocking the main thread.
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.
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 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.
Here's a basic example of creating an async method:
csharppublic async Task<string> GetDataAsync() { // Simulate a delay (e.g., a web request) await Task.Delay(2000); return "Data retrieved!"; }
To call an asynchronous method, you also use await:
csharppublic async Task ExecuteAsync() { string result = await GetDataAsync(); Console.WriteLine(result); }
we can also handle exceptions in async methods using try-catch blocks:
csharppublic async Task<string> GetDataAsync() { try { await Task.Delay(2000); throw new Exception("Error occurred!"); } catch (Exception ex) { Console.WriteLine(ex.Message); return "Error handled."; } }
Web API Call: here in this example, we are calling the web API asynchronously:
csharpusing 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.
Copyrights © 2024 letsupdateskills All rights reserved