Codementor Events

The use of asynchronous programming in C#?

Published Feb 10, 2024

Asynchronous programming in C# allows you to write non-blocking code, which is crucial for handling operations that may take time to complete, such as I/O-bound operations (like reading from files or making network requests). It ensures that your application remains responsive and doesn't freeze while waiting for these operations to finish.

Here's an overview of how asynchronous programming works in C#:

Async and Await Keywords: These keywords were introduced in C# 5.0 to simplify asynchronous programming. The async keyword is used to mark a method as asynchronous, and the await keyword is used to asynchronously wait for the completion of a task.

Task and Task<T> Types: The Task and Task<T> types represent asynchronous operations that may return a result. You can use these types to manage and await asynchronous operations.

Async Methods: Async methods return either void, Task, or Task<T>. They can contain the await keyword, which allows the method to asynchronously wait for the completion of another asynchronous operation.

Here's a simple example:

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

class Program
{
    static async Task Main(string[] args)
    {
        await MakeNetworkRequestAsync();
        Console.WriteLine("Operation completed.");
    }

    static async Task MakeNetworkRequestAsync()
    {
        using (HttpClient client = new HttpClient())
        {
            string response = await client.GetStringAsync("https://jsonplaceholder.typicode.com/posts/1");
            Console.WriteLine(response);
        }
    }
}

In this example, MakeNetworkRequestAsync() method asynchronously retrieves data from a URL using HttpClient.GetStringAsync(). The await keyword is used to wait for the completion of this asynchronous operation without blocking the main thread.

Async Streams: Starting from C# 8.0, you can use async streams to asynchronously produce a sequence of data. This is useful when dealing with operations that produce data over time, such as reading from a file or receiving data over a network stream.
Here's a simplified example of async streams:

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

class Program
{
  static async Task Main(string[] args)
  {
      await foreach (var line in ReadLinesAsync("example.txt"))
      {
          Console.WriteLine(line);
      }
  }

  static async IAsyncEnumerable<string> ReadLinesAsync(string filePath)
  {
      using (StreamReader reader = File.OpenText(filePath))
      {
          string line;
          while ((line = await reader.ReadLineAsync()) != null)
          {
              yield return line;
          }
      }
  }
}

In this example, ReadLinesAsync() asynchronously reads lines from a text file and yields each line as it becomes available.

These are just some of the basics of asynchronous programming in C#. Asynchronous programming allows you to write more scalable and responsive applications, especially when dealing with I/O-bound operations. However, it's essential to understand the concepts and use them appropriately to avoid potential issues such as deadlocks or performance bottlenecks.

Discover and read more posts from DOMINIC OWOICHO JAMES
get started
post commentsBe the first to share your opinion
Show more replies