How to create Threads in C#
In C#, you can create threads using the System.Threading namespace. Here is an example code snippet:
C#
using System;
using System.Threading;
class Program {
static void Main() {
Thread thread = new Thread( new ThreadStart(Worker));
thread.Start();
for ( int i = 0; i < 5; i++) {
Console.WriteLine( "Main thread: {0}" , i);
Thread.Sleep(100);
}
thread.Join();
}
static void Worker() {
for ( int i = 0; i < 5; i++) {
Console.WriteLine( "Worker thread: {0}" , i);
Thread.Sleep(100);
}
}
}
|
Output
Main thread: 0
Worker thread: 0
Main thread: 1
Worker thread: 1
Main thread: 2
Worker thread: 2
Main thread: 3
Worker thread: 3
Main thread: 4
Worker thread: 4
In this example, we create a new thread using the Thread class and passing in a delegate to the Worker method. We then start the thread using the Start method.
In the Main method, we do some work in the main thread and then wait for the worker thread to finish using the Join method.
In the Worker method, we do some work in the worker thread.
Note that when creating threads, you should always make sure to properly synchronize access to shared data between threads to avoid race conditions and other synchronization issues.
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 :
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }Â
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:
- 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
- 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));
}
- 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:
CSharp
using System;
using System.Threading;
public class ExThread {
public void mythread1()
{
for ( int z = 0; z < 3; z++) {
Console.WriteLine("First Thread");
}
}
}
public class GFG {
public static void Main()
{
ExThread obj = new ExThread();
Thread thr = new Thread( new ThreadStart(obj.mythread1));
thr.Start();
}
}
|
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:
CSharp
using System;
using System.Threading;
public class ExThread {
public static void thread1()
{
for ( int z = 0; z < 5; z++) {
Console.WriteLine(z);
}
}
public static void thread2()
{
for ( int z = 0; z < 5; z++) {
Console.WriteLine(z);
}
}
}
public class GFG {
public static void Main()
{
Thread a = new Thread(ExThread.thread1);
Thread b = new Thread(ExThread.thread2);
a.Start();
b.Start();
}
}
|
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.
Last Updated :
21 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...