Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to pass Parameter to a Thread
To work with threads in C#, you need to add the System.Threading namespace. Passing parameters to threads allows you to send data from the main thread to worker threads, enabling more flexible and dynamic thread operations.
Syntax
Following is the syntax for creating a thread and passing a parameter −
Thread thread = new Thread(ThreadMethod); thread.Start(parameter);
The thread method must accept an object parameter −
static void ThreadMethod(object parameter) {
// cast parameter to appropriate type
}
Using Thread.Start() with a Parameter
The Thread.Start(object) method accepts a single parameter of type object. Inside the thread method, you need to cast this parameter to the appropriate type −
using System;
using System.Threading;
class Demo {
static void Main(string[] args) {
String str = "Hello World!";
// new thread
Thread thread = new Thread(threadDemo);
// passing parameter
thread.Start(str);
// wait for thread to complete
thread.Join();
}
static void threadDemo(object str) {
Console.WriteLine("Value passed to the thread: " + str);
}
}
The output of the above code is −
Value passed to the thread: Hello World!
Passing Multiple Parameters
Since Thread.Start() accepts only one parameter, you can pass multiple values using a custom class or struct −
using System;
using System.Threading;
class ThreadData {
public string Name;
public int Age;
public ThreadData(string name, int age) {
Name = name;
Age = age;
}
}
class Demo {
static void Main(string[] args) {
ThreadData data = new ThreadData("John", 25);
Thread thread = new Thread(ProcessData);
thread.Start(data);
thread.Join();
}
static void ProcessData(object obj) {
ThreadData data = (ThreadData)obj;
Console.WriteLine("Name: " + data.Name + ", Age: " + data.Age);
}
}
The output of the above code is −
Name: John, Age: 25
Using ParameterizedThreadStart Delegate
You can also explicitly use the ParameterizedThreadStart delegate for better type safety −
using System;
using System.Threading;
class Demo {
static void Main(string[] args) {
int number = 42;
ParameterizedThreadStart threadStart = new ParameterizedThreadStart(DisplayNumber);
Thread thread = new Thread(threadStart);
thread.Start(number);
thread.Join();
}
static void DisplayNumber(object num) {
int value = (int)num;
Console.WriteLine("Thread received number: " + value);
Console.WriteLine("Square of the number: " + (value * value));
}
}
The output of the above code is −
Thread received number: 42 Square of the number: 1764
Conclusion
Passing parameters to threads in C# is accomplished using the Thread.Start(object) method. For single parameters, pass the value directly; for multiple parameters, use a custom class or struct to encapsulate the data.
