Lesson: C# Multithreading

What is Multithreading in C#?

Multithreading allows your program to perform multiple operations simultaneously. In C#, this is accomplished using the Thread class or higher-level constructs like Task and async/await.

Basic Threading Example

Below is an example of a basic multithreaded application that runs two tasks in parallel:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        Thread thread1 = new Thread(PrintNumbers);
        Thread thread2 = new Thread(PrintLetters);

        thread1.Start();
        thread2.Start();
    }

    static void PrintNumbers()
    {
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine(i);
            Thread.Sleep(1000); // Pauses for 1 second
        }
    }

    static void PrintLetters()
    {
        char letter = 'A';
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine(letter);
            letter++;
            Thread.Sleep(1500); // Pauses for 1.5 seconds
        }
    }
}
        

This example creates two threads. One prints numbers, and the other prints letters. They run in parallel, and the outputs are interleaved.

Thread Synchronization

When multiple threads access shared data, synchronization is essential to avoid conflicts. You can use the lock keyword to ensure that only one thread can access a particular section of code at a time.

class Program
{
    static int count = 0;
    static readonly object lockObj = new object();

    static void Main()
    {
        Thread thread1 = new Thread(IncrementCount);
        Thread thread2 = new Thread(IncrementCount);

        thread1.Start();
        thread2.Start();
    }

    static void IncrementCount()
    {
        for (int i = 0; i < 1000; i++)
        {
            lock (lockObj)
            {
                count++;
            }
        }
        Console.WriteLine("Final count: " + count);
    }
}
        

In the above code, lock (lockObj) ensures that only one thread can increment the count at a time, preventing race conditions.

Quiz: Test Your Knowledge

1. What is the primary advantage of multithreading?




2. What happens if two threads try to access the same resource at the same time without synchronization?




3. What is the purpose of the Thread.Sleep() method?




4. How can you ensure that only one thread can access a critical section of code at a time?




5. Which method is used to pause the execution of a thread for a specified amount of time?