C Sharp multithreading examples

C# Threading Example

On the execution of the thread, either of the static and non-static methods can be called by passing the method name in the constructor of ThreadStart class.

Example 1: Static Method:

using System;  
using System.Threading;  
public class Example  
{  
    public static void thr()  
    {  
        for (char i = 'a'; i < 'g'; i++)  
        {  
            Console.WriteLine(i);  
        }  
    }  
}  
public class thr2  
{  
    public static void Main()  
    {  
        Thread x = new Thread(new ThreadStart(Example.thr));  
        Thread y = new Thread(new ThreadStart(Example.thr));  
        x.Start();  
        y.Start();  
    }  
}

Output:

Explanation:

In the above example, we are using the static method. Thus, there is no need to create the instance of the class. It can be referred to by the name of the class. Since there is a context switching between the threads, thus the output of the above code can be anything.

Example 2: Non-static method:

using System;  
using System.Threading;  
public class Example  
{  
    public void thr()  
    {  
        for (char i = 'a'; i < 'g'; i++)  
        {  
            Console.WriteLine(i); 
        }  
    }  
}  
public class thr2  
{  
    public static void Main()  
    {  
        Example thrd = new Example();  
        Thread x = new Thread(new ThreadStart(thrd.thr));  
        Thread y = new Thread(new ThreadStart(thrd.thr));  
        x.Start();  
        y.Start();  
    }  
}

Output:

Explanation:

In the above example, we are using the non-static method. Thus, an instance of the class needs to be created to refer to it in the constructor of the ThreadStart class. Since there is a context switching between the threads, thus the output of the above code can be anything.

Example 3:

using System;  
using System.Threading;  
 
public class Example  
{  
    public static void thrd1()  
    {  
        Console.WriteLine("Hello World!!");  
    }  
    public static void thrd2()  
    {  
        Console.WriteLine("Today is a great day!!");  
    }  
}  
public class thrd  
{  
    public static void Main()  
    {  
        Thread x = new Thread(new ThreadStart(Example.thrd1));  
        Thread y = new Thread(new ThreadStart(Example.thrd2));  
        x.Start();  
        y.Start();  
    }  
}

Output:

Explanation:

In the above example, we are performing different tasks on each thread. Here, different methods are executed on each thread.