Asynchronous programming in C#

by mahidhar

Asynchronous programming in C# helps improve application performance by running tasks concurrently.

Async and Await:

code
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace NationalParks
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string url = "https://example.com";
            string result = await FetchDataAsync(url);
            Console.WriteLine(result);
        }

        static async Task<string> FetchDataAsync(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
        }
    }
}

Task Parallel Library (TPL):

code
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace NationalParks
{
    class Program
    {
        static async Task Main(string[] args)
        {
            List<Task> tasks = new List<Task>
            {
                Task.Run(() => ProcessData("Yellowstone")),
                Task.Run(() => ProcessData("Yosemite")),
                Task.Run(() => ProcessData("Zion"))
            };

            await Task.WhenAll(tasks);
            Console.WriteLine("All tasks completed.");
        }

        static void ProcessData(string parkName)
        {
            Console.WriteLine($"Processing data for {parkName}");
            // Simulate work
            Task.Delay(1000).Wait();
            Console.WriteLine($"{parkName} processing completed.");
        }
    }
}

Choosing Asynchronous Patterns:

Use async and await for I/O-bound operations (e.g., web requests, file I/O).
Use TPL for CPU-bound operations (e.g., data processing, calculations).
Performance Considerations:

Benchmarking can help determine the best approach. Asynchronous methods reduce blocking, improving responsiveness and resource utilization.
Consider using profiling tools to measure memory usage and execution time.
Graph for Benchmarking (Hypothetical):

Pattern Memory

Execution Time (ms)

Usage (MB)

Sequential Processing

3000

50

Parallel Processing (TPL)

1200

80

Async/Await (I/O-bound)

1500

60

Explanation:

Parallel processing with TPL significantly reduces execution time for CPU-bound tasks.
Async/await is beneficial for I/O-bound tasks, reducing the overall application blocking time.

Conclusion
Understanding collections, LINQ, exception handling, and asynchronous programming is crucial for developing efficient, scalable, and robust applications. Asynchronous programming with async/await and TPL improves responsiveness and resource utilization, especially in large-scale applications.