Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Parameters through ParameterizedThreadStart

I'm trying to pass parameters through the following:

Thread thread = new Thread(new ParameterizedThreadStart(DoMethod)); 

Any idea how to do this? I'd appreciate some help

like image 755
liamp47 Avatar asked Dec 08 '12 11:12

liamp47


People also ask

What is ParameterizedThreadStart in C#?

C# | Thread(ParameterizedThreadStart) Constructor Thread(ParameterizedThreadStart) Constructor is used to initialize a new instance of the Thread class. It defined a delegate which allows an object to pass to the thread when the thread starts.

What is Threadpool C#?

Thread pool in C# is a collection of threads. It is used to perform tasks in the background. When a thread completes a task, it is sent to the queue wherein all the waiting threads are present. This is done so that it can be reused.

How do I start a thread in C#?

Create New Thread [C#] First, create a new ThreadStart delegate. The delegate points to a method that will be executed by the new thread. Pass this delegate as a parameter when creating a new Thread instance. Finally, call the Thread.


1 Answers

lazyberezovsky has the right answer. I want to note that technically you can pass an arbitrary number of arguments using lambda expression due to variable capture:

var thread = new Thread(        () => DoMethod(a, b, c)); thread.Start(); 

This is a handy way of calling methods that don't fit the ThreadStart or ParameterizedThreadStart delegate, but be careful that you can easily cause a data race if you change the arguments in the parent thread after passing them to the child thread's code.

like image 189
Tudor Avatar answered Oct 03 '22 12:10

Tudor