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:
// 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();
}
}
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:
// 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();
}
}
Output
Money Talk
Create thread in C#
Submitted by diron, 03-06-2019, 10:54 PM, Thread ID: 132393
Thread Closed
How to create thread in C#
Create thread in C#
Votes:
6
% of votes:
100.00%
Language C# thread
Votes:
0
% of votes:
0%
You have already voted. Click on the dropdown to undo your vote.