Basic example of Multithreading

Basic example of Multithreading

Multithreading allows you to execute multiple threads or tasks concurrently, enhancing the performance and responsiveness of your application. In this article, we’ll walk through a basic example of multithreading in C# and demonstrate how to run parallel tasks.

Creating a Basic Multithreading Example

Let’s start by creating a simple console application that calculates the sum of numbers using a single thread.

using System;

class Program
{
    static void Main()
    {
        int sum = 0;

        for (int i = 1; i <= 100; i++)
        {
            sum += i;
        }

        Console.WriteLine($"Sum of numbers: {sum}");
        Console.ReadLine();
    }
}

This code calculates the sum of numbers from 1 to 100 using a loop. The output will be displayed on the console.

Introducing Multithreading

Now, let’s introduce multithreading to make the calculation of the sum more efficient. We can achieve this by running multiple threads, each responsible for calculating a portion of the sum.

using System;
using System.Threading;

class Program
{
    static int sum = 0;

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

        thread1.Start(1);
        thread2.Start(51);

        thread1.Join();
        thread2.Join();

        Console.WriteLine($"Sum of numbers: {sum}");
        Console.ReadLine();
    }

    static void CalculatePartialSum(object start)
    {
        int partialSum = 0;
        int startPosition = (int)start;

        for (int i = startPosition; i <= startPosition + 49; i++)
        {
            partialSum += i;
        }

        Interlocked.Add(ref sum, partialSum);
    }
}

In this updated code, we create two threads, thread1 and thread2, each responsible for calculating a portion of the sum. The CalculatePartialSum method is invoked by each thread and calculates the partial sum for the specified range of numbers. The Interlocked.Add method is used to safely add the partial sum to the overall sum.

By running multiple threads, the computation of the sum is now divided among the threads, reducing the overall execution time.

Conclusion

Multithreading offers a powerful way to improve the performance of your C# applications by running tasks in parallel. In this article, we covered a basic example of multithreading, demonstrating how to use multiple threads to calculate the sum of numbers.

Keep in mind that multithreading requires careful consideration, especially when accessing shared data or synchronizing thread operations. Always make sure to handle thread synchronization and data access to avoid race conditions and other multithreading-related issues.

To learn more about multithreading in C# and explore more advanced concepts, refer to the official Microsoft documentation and further resources available online.

Happy coding!