C# program to create a new thread
To create a new thread object in the C# program, follow the below steps:
Step 1: Import the required namespace, as below:
Step 2: Create a function that you need to call/execute along with this thread. you can create this function in the same class or in a separate class based on your project structure, I have created it in a separate class "MyProcess" as below.
class MyProcess
{
public void MyThreadFun()
{
int i = 0;
for (i = 1; i <= 4; i++)
{
Console.WriteLine("This is My Thread process...");
}
}
}
Step 3: Create an object of this class so that you can get the reference of the functions of this class to pass in the ThreadStart delegate as below:
MyProcess process = new MyProcess();
ThreadStart threadDelegate = new ThreadStart(process.MyThreadFun);
Step 4: Create an object reference of the "Thread" class in the main function or at the location where you want to create this Thread with delegate reference of ThreadStart created in step 3.
Thread t1 = new Thread(threadDelegate);
Step 5: At Last, just use this thread object "t1" to start this thread at any event, as below:
t1.Start();
Full Program to create a new thread in C#:
The source code to create a thread in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
/*
* Program to create a threads in C# Programming
*/
using System;
using System.Threading;
namespace ConsoleApp1
{
class MyProcess
{
public void MyThreadFun()
{
int i = 0;
for (i = 1; i <= 4; i++)
{
Console.WriteLine("This is My Thread process...");
}
}
}
class Program
{
public static void Main()
{
MyProcess process = new MyProcess();
ThreadStart threadDelegate = new ThreadStart(process.MyThreadFun);
Thread t1 = new Thread(threadDelegate);
t1.Start();
}
}
}
Output:
I hope this helps, feel free to comment below for any questions.