[Code] C# - Simple way to pass parameters to Thread() method and invoke control

First Post:

Last Update:

Word Count:
324

Read Time:
2 min

Abstract

Today, I’ll share a straightforward approach to passing parameters to the Thread method in C#. I’ll also cover how to invoke a control safely within a thread.

The Common Approach You See Online

This is what I saw in online:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void Function1(object data)
{
//SOME CODE...
}

void Function2(object data)
{
object[] objs = (object[])data; //Convert object into object array.
int x = (int)objs[0]; //Convert 1st element into integer.
string y = (string)objs[1]; //Convert 2nd element into integer.

//SOME CODE.....
}

//Function 1
object obj = "Hello world!";
Thread thread1 = new Thread(new ParameterizedThreadStart(Function1));
thread1.Start(obj);

//Function 2
object[] objs = new object[] { 666, "What?" };
Thread thread1 = new Thread(new ParameterizedThreadStart(Function2));
thread1.Start(objs);


This method works but feels clunky and error-prone. It involves boxing/unboxing and manually unpacking parameters, which isn’t ideal.

A Simpler Way to Pass Parameters

We can use the lamda function

1
2
3
4
5
6
7
8
void Function(int x, string y)
{
//SOME CODE.....
}

Thread thread = new Thread(() => Function(666, "Good"));
thread.Start();


With this approach, the Thread constructor doesn’t need a separate method like ParameterizedThreadStart. Instead, the lambda expression lets you pass the exact arguments to your method.

Going Even Further

If you don’t need to reuse the thread reference, you can make it even cleaner

1
2
3
4
5
6
void Function(int x, string y)
{
//SOME CODE.....
}

new Thread(() => Function(666, "Nice")).Start();

This method eliminates the need for intermediate objects entirely. It’s cleaner, concise, and less error-prone.

Addition

More elegant ways

1
2
3
4
5
6
7
void Function(int x, string y)
{
// SOME CODE...
}

Task.Run(() => Function(666, "Oh..."));


This is concise, highly readable, and works seamlessly with async/await patterns.


1
2
3
4
5
6
void Function(int x, string y)
{
// SOME CODE...
}

ThreadPool.QueueUserWorkItem(_ => Function(666, "ThreadPool"));

Thread pooling is efficient and avoids the overhead of creating a dedicated thread for every task!