Synchronous Programming

Asynchronous Programming

// Synchronous code
public void SynchronousMethod()
{
    Console.WriteLine("Start synchronous operation");
    Task.Delay(2000).Wait(); // Simulate a time-consuming operation
    Console.WriteLine("Synchronous operation completed");
}

// Asynchronous code
public async Task AsynchronousMethod()
{
    Console.WriteLine("Start asynchronous operation");
    await Task.Delay(2000); // Simulate a time-consuming operation asynchronously
    Console.WriteLine("Asynchronous operation completed");
}

In the synchronous method, Task.Delay(2000).Wait() blocks the current thread for 2 seconds before proceeding, whereas in the asynchronous method, await Task.Delay(2000) allows the program to continue executing other tasks while waiting for the delay to complete.

Synchronous Web Request

using System;
using System.Net;

public class Program
{
    public static void Main(string[] args)
    {
        // Synchronous web request
        WebClient client = new WebClient();
        string content = client.DownloadString("https://example.com");
        Console.WriteLine("Web content (synchronous):");
        Console.WriteLine(content);
    }
}

Asynchronous Web Request

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

public class Program
{
    public static async Task Main(string[] args)
    {
        // Asynchronous web request
        HttpClient client = new HttpClient();
        string content = await client.GetStringAsync("https://example.com");
        Console.WriteLine("Web content (asynchronous):");
        Console.WriteLine(content);
    }
}

These examples demonstrate the differences between synchronous and asynchronous programming in .NET, particularly in scenarios involving file I/O and web requests. Asynchronous programming can significantly improve the responsiveness and scalability of applications, especially in scenarios where there are many concurrent operations.