Multithreading

Multithreading in C# enables multiple threads to execute simultaneously, allowing your application to perform various tasks at the same time. This capability can enhance the responsiveness and efficiency of programs, particularly when handling tasks that can be executed in parallel, such as input/output operations, computations, or managing multiple client requests.

Basics of Multithreading

  • Thread Class: The ‘Thread’ class, found in the ‘System.Threading’ namespace, is utilized to create and manage threads.
  • Thread.Start Method: The ‘Thread.Start()’ method initiates the execution of a thread.
  • Creating Threads with Delegates: Threads can be instantiated from methods using delegates. The ‘ThreadStart’ delegate is used for parameterless methods, while ‘ParameterizedThreadStart’ is used for methods that accept an object parameter.
  • Synchronization: It is crucial to synchronize access to shared resources using locks to prevent data corruption and ensure thread safety.

Example

using System;
using System.Threading;

// Class to perform tasks
class TaskHandler
{
  // Method to print numbers
  public void PrintNumbers()
  {
      for (int i = 1; i <= 5; i++)
      {
          Console.WriteLine($"Number: {i}");
          Thread.Sleep(1000); // Simulate some work with a delay
      }
  }

    // Method to print letters
  public void PrintLetters()
  {
      for (char c = 'A'; c <= 'E'; c++)
      {
          Console.WriteLine($"Letter: {c}");
          Thread.Sleep(1000); // Simulate some work with a delay
      }
  }
}

class
Program
{
  static void Main()
  {
      TaskHandler handler = new TaskHandler();

     
// Create threads for each task
      Thread thread1 = new Thread(new ThreadStart(handler.PrintNumbers));
      Thread thread2 = new Thread(new ThreadStart(handler.PrintLetters));

        // Start the threads
      thread1.Start();
      thread2.Start();

        // Wait for threads to finish
      thread1.Join();
      thread2.Join();
      Console.WriteLine("Both tasks are completed.");
  }
}

Explanation of the Example

  1. Class Definition (TaskHandler):
    • We define a class called ‘TaskHandler’ that includes two methods: ‘PrintNumbers’ and ‘PrintLetters’.
    • The ‘PrintNumbers’ method prints numbers from 1 to 5, with a 1-second delay between each print.
      The ‘PrintLetters’ method prints letters from ‘A’ to ‘E’, also with a 1-second delay between each print.
  2. Thread Creation:
    • In the ‘Main’ method, we create an instance of ‘TaskHandler’.
    • We then create two threads- ‘thread1’ for the ‘PrintNumbers’ method, and ‘thread2’ for the ‘PrintLetters’ method, using the ‘ThreadStart’ delegate.
  3. Thread Execution:
    • We start the threads using the ‘Start’ method, which begins the concurrent execution of ‘PrintNumbers’ and ‘PrintLetters’.
    • To ensure that both threads complete their execution before moving on, we use the `Join` method to wait for them to finish.
  4. Output:
    • The output will display numbers and letters printed concurrently, demonstrating the execution of multiple threads.

Key Concepts

  • Concurrency: Threads execute concurrently, allowing multiple tasks to run simultaneously, thereby improving performance and responsiveness.
  • Thread Safety: When dealing with shared resources, it is important to ensure thread safety by using synchronization mechanisms, such as ‘lock’.
  • Thread Management: Use the ‘Start’ method to initiate thread execution and the ‘Join’ method to wait for a thread to complete.
Post a comment

Leave a Comment

Scroll to Top