C# Language
Asynchronous Programming in C#:
Asynchronous programming in C# allows you to perform long-running tasks without blocking the execution thread. This is particularly useful in scenarios like network operations, file I/O, or any operation that might take a significant amount of time.
1. Async and Await Keywords: The 'async' and 'await' are two keywords introduced in C# 5.0 to simplify asynchronous programming.
• async: This keyword is used to define a method as asynchronous. It doesn't necessarily mean the method will run asynchronously, but it allows the method to use the 'await' keyword.
• await: This keyword is used inside an async method to asynchronously wait for the completion of a task. It tells the compiler that the method should pause until the awaited task is complete, allowing the calling thread to continue executing other work.
2. Task and Task<T>: In asynchronous programming, you often work with the 'Task' class or its generic counterpart 'Task<T>'. A 'Task' represents an asynchronous operation, while' Task<T>' represents an asynchronous operation that returns a result of type 'T'.
3. Returning Task and Task<T>: Async methods return either 'Task' or 'Task<T>'. If the method returns 'void', it can be made asynchronous by returning 'Task'. If it returns a result, you can make it asynchronous by returning 'Task<T>'.
4. Error Handling: Error handling in asynchronous methods can be done using try-catch blocks inside the method, just like synchronous methods. Additionally, you can handle errors from awaited tasks using try-catch blocks around 'await' statements.
5. Async in LINQ Queries: Starting from C# 7.0, you can use 'async' and 'await' in LINQ queries, allowing you to perform asynchronous operations within LINQ queries.
• Programing example:
using System; using System.Threading.Tasks; class Program { static async Task<int> FetchDataAsync() { // Simulating asynchronous operation await Task.Delay(1000); // Wait for 1 second return 42; } static async Task Main() { Console.WriteLine("Fetching data..."); int result = await FetchDataAsync(); Console.WriteLine($"Data fetched: {result}"); } }
Fetching data... Data fetched: 42
Key Takeaways:
• Async and await in C# simplify asynchronous programming by allowing you to write code that looks synchronous but behaves asynchronously.
• Asynchronous programming improves the responsiveness of applications, especially in scenarios where waiting for I/O operations.
• Proper error handling is crucial in asynchronous methods to handle exceptions effectively.
Note: Async and await are powerful features in C# that enable developers to write more responsive and scalable applications, especially in scenarios involving I/O-bound operations.
• Write a program in C# to fetch data from a server:
using System; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task<string> FetchDataAsync() { string url = "https://www.techbaz.org/about.txt"; using HttpClient client = new(); HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStringAsync(); } else { throw new Exception($"Fetch Failed {url}. Code: {response.StatusCode}"); } } static async Task Main() { Console.WriteLine("Fetching data..."); string result = await FetchDataAsync(); Console.WriteLine($"Data fetched: {result}"); } }
Data fetched: -> 'Techbaz' is a project of free IT education.
⤏ This program will fetch the content of the specified URL asynchronously using 'HttpClient', and then print the fetched data. Make sure to include the necessary 'using' directives for 'HttpClient' and 'HttpResponseMessage'.
What's Next?
We've now entered the finance section on this platform, where you can enhance your financial literacy.