Home »
.Net »
C# Programs
C# - How to Pass Parameter to Thread?
Here, we are going to learn the concept of parameter passing for thread in C#?
By Nidhi Last updated : March 29, 2023
In this C# program, we're demonstrating the example of parameter passing in the static and instance thread methods.
C# program to pass parameter to thread
/*
* Program to demonstrate the concept of
* parameter passing for thread in C#.
*/
using System;
using System.Threading;
public class MyThreadClass {
public static void StaticThreadMethod(object param) {
Console.WriteLine("StaticThreadMethod:param->" + param);
}
public void InstanceThreadMethod(object param) {
Console.WriteLine("InstanceThreadMethod:param->" + param);
}
public static void Main() {
Thread T = new Thread(MyThreadClass.StaticThreadMethod);
T.Start(100);
MyThreadClass p = new MyThreadClass();
T = new Thread(p.InstanceThreadMethod);
T.Start(200);
}
}
Output
StaticThreadMethod:param->100
InstanceThreadMethod:param->200
Press any key to continue . . .
Explanation
In the above program, we created a class MyThreadClass that contains one static method StaticThreadMethod() and an instance method InstanceThreadMethod. Both method accept the argument of object type and print then on the console screen. The MyThreadClass also contains a Main() method.
In the Main() method we created a thread T.
Thread T = new Thread(MyThreadClass.StaticThreadMethod);
T.Start(100);
Here we bind the StaticThreadethod() with thread T and pass value 100 as a parameter.
MyThreadClass p = new MyThreadClass();
T = new Thread(p.InstanceThreadMethod);
T.Start(200);
Here we bind the InstanceThreadethod() with thread T and pass value 200 as a parameter.
C# Thread Programs »