Multithreading In C# .NET

Introduction

If you have a program that executes from top to bottom, it will not be responsive and feasible to build complex applications. So, the .NET Framework offers some classes to create complex applications.

What is threading?

In short, the thread is like a virtualized CPU which will help to develop complex applications.

Understanding threading

Suppose you have a computer that only has one CPU capable of executing only one operation at a time. And your application has a complex operation. So, in this situation, your application will take too much time. This means that the whole machine will freeze and appear unresponsive. So your application performance will decrease.

To protect the performance, we will be multithreading in C#.NET. So, we will divide our program into different parts using threading. And you know, every application runs its own process in Windows. So every process will run in its own thread.

Thread Class

Thread class can be found in System. Threading namespace, Using this class, you can create a new thread and manage the program, like property, status, etc., of your thread.

Example. The following code shows how to create a thread in C#.NET.

using System;
using System.Threading;
class Program
{
    private static void LoopTask()
    {
        for (int x = 0; x < 10; x++)
        {
            Console.WriteLine("X => {0}", x);
            Thread.Sleep(1000);
        }
    }
    static void Main(string[] args)
    {
        ThreadStart thread = new ThreadStart(LoopTask);
        Thread myThread = new Thread(thread);
        myThread.Start();
        for (int y = 0; y < 4; y++)
        {
            Console.WriteLine("Main thread.");
            Thread.Sleep(1000);
        }
        Console.ReadKey();
    }
}

Explanation

You may observe that I created a new Local Variable thread of ThreadStart delegate and passed loopTask as a parameter to execute it. This loopback Function has a loop. We create a new object myThread, from Thread Class and pass the Local Variable thread to Thread Constructor. And start the Thread using myThread.Start(); and Thread.Sleep(2000); will pause for 2000 milliseconds.

And finally, the result will be.

C#

This code also can be written in a more simple way like this.

using System;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        new Thread(new ThreadStart(() =>
        {
            for (int x = 0; x < 10; x++)
            {
                Console.WriteLine("X => {0}", x);
                Thread.Sleep(1000);
            }
        })).Start();
        Console.ReadKey();
    }
}

In the above code, we are using lambda expression ( => ) for initialization.

Passing Value as Parameter

The Thread constructor has another overload that takes an instance of a ParameterizedThreadStart delegate. It can be used if you want to pass some data through the start method of your thread to your method.

using System;
using System.Threading;
class Program
{
    private static void LoopTask(object value)
    {
        for (int x = 0; x < 10; x++)
        {
            Console.WriteLine("X => {0} And Parameter Value is => {1}", x, value);
            Thread.Sleep(1000);
        }
    }
    static void Main(string[] args)
    {
        Thread myThread = new Thread(new ParameterizedThreadStart(LoopTask));
        myThread.Start("Kashif");
        Console.ReadKey();
    }
}

In this case, the value 5 is passed to the loopTask as an object. You can cast it to the expected type.


Similar Articles