How to create Threads in C#

In C#, a multi-threading system is built upon the Thread class, which encapsulates the execution of threads. This class contains several methods and properties which helps in managing and creating threads and this class is defined under System.Threading namespace. The System.Threading namespace provides classes and interfaces that are used in multi-thread programming.

Some commonly used classes in this namespace are :

Class Name Description
Mutex It is a synchronization primitive that can also be used for IPS (interprocess synchronization).
Monitor This class provides a mechanism that access objects in synchronize manner.
Semaphore This class is used to limit the number of threads that can access a resource or pool of resources concurrently.
Thread This class is used to creates and controls a thread, sets its priority, and gets its status.
ThreadPool This class provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.
ThreadLocal This class provides thread-local storage of data.



Timer This class provides a mechanism for executing a method on a thread pool thread at specified intervals. You are not allowed to inherit this class.
Volatile This class contains methods for performing volatile memory operations.

Steps to create a thread in a C# Program:

  1. First of all import System.Threading namespace, it plays an important role in creating a thread in your program as you have no need to write the fully qualified name of class everytime.
    Using System;
    Using System.Threading
    
  2. Now, create and initialize the thread object in your main method.
    public static void main()
    {
        Thread thr = new Thread(job1);
    }
    

    Or

    You can also use ThreadStart constructor for initializing a new instance.

    public static void main()
    {
         Thread thr = new Thread(new ThreadStart(job1));
    }
    
  3. Now you can call your thread object.
    public static void main()
    {
        Thread thr = new Thread(job1);
        thr.Start();
    }
    

Below programs illustrate the practical implementations of above steps:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the
// creation of thread using
// non-static method
using System;
using System.Threading;
  
public class ExThread {
  
    // Non-static method
    public void mythread1()
    {
        for (int z = 0; z < 3; z++) {
            Console.WriteLine("First Thread");
        }
    }
}
  
// Driver Class
public class GFG {
  
    // Main Method
    public static void Main()
    {
        // Creating object of ExThread class
        ExThread obj = new ExThread();
  
        // Creating thread
        // Using thread class
        Thread thr = new Thread(new ThreadStart(obj.mythread1));
        thr.Start();
    }
}

chevron_right


Output:

First Thread
First Thread
First Thread

Explanation: In the above example, we have a class named as ExThread that contain a non-static method named as mythread1(). So we create an instance, i.e. obj of ExThread class and refer it in the constructor of ThreadStart class as given in this statement Thread a = new Thread(new ThreadStart(obj.mythread1));. Using Thread a = new Thread(new ThreadStart(obj.mythread1)); statement we will create a thread named as thr and initialize the work of this thread. By using thr.Start(); statement.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to illustrate the creation
// of thread using static method
using System;
using System.Threading;
  
public class ExThread {
  
    // Static method for thread a
    public static void thread1()
    {
        for (int z = 0; z < 5; z++) {
            Console.WriteLine(z);
        }
    }
  
    // static method for thread b
    public static void thread2()
    {
        for (int z = 0; z < 5; z++) {
            Console.WriteLine(z);
        }
    }
}
  
// Driver Class
public class GFG {
  
    // Main method
    public static void Main()
    {
        // Creating and initializing threads
        Thread a = new Thread(ExThread.thread1);
        Thread b = new Thread(ExThread.thread2);
        a.Start();
        b.Start();
    }
}

chevron_right


Output :

0
1
2
3
4
0
1
2
3
4

Explanation: In the above example, we have a class named as ExThread and contain two static methods named as thread1() and thread2(). So we do not need to create an instance of ExThread class. Here we call these methods using a class name, like ExThread.thread1, ExThread.thread2. By using Thread a = new Thread(ExThread.thread1); statement we create and initialize the work of thread a, similarly for thread b. By using a.Start(); and b.Start(); statements, a and b threads scheduled for execution.

Note: The output of these programs may vary due to context switching.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.