c# - ThreadStart with parameters

ID : 10312

viewed : 17

Tags : c#multithreadingc#

Top 5 Answer for c# - ThreadStart with parameters

vote vote

100

One of the 2 overloads of the Thread constructor takse a ParameterizedThreadStart delegate which allows you to pass a single parameter to the start method. Unfortunately though it only allows for a single parameter and it does so in an unsafe way because it passes it as object. I find it's much easier to use a lambda expression to capture the relevant parameters and pass them in a strongly typed fashion.

Try the following

public Thread StartTheThread(SomeType param1, SomeOtherType param2) {   var t = new Thread(() => RealStart(param1, param2));   t.Start();   return t; }  private static void RealStart(SomeType param1, SomeOtherType param2) {   ... } 
vote vote

80

Yep :

Thread t = new Thread (new ParameterizedThreadStart(myMethod)); t.Start (myParameterObject); 
vote vote

71

You can use lambda expressions

private void MyMethod(string param1,int param2) {   //do stuff } Thread myNewThread = new Thread(() => MyMethod("param1",5)); myNewThread.Start(); 

this is so far the best answer i could find, it's fast and easy.

vote vote

65

Thread thread = new Thread(Work); thread.Start(Parameter);  private void Work(object param) {     string Parameter = (string)param; } 

The parameter type must be an object.

EDIT:

While this answer isn't incorrect I do recommend against this approach. Using a lambda expression is much easier to read and doesn't require type casting. See here: https://stackoverflow.com/a/1195915/52551

vote vote

57

class Program {     static void Main(string[] args)     {         Thread t = new Thread(new ParameterizedThreadStart(ThreadMethod));          t.Start("My Parameter");     }      static void ThreadMethod(object parameter)     {         // parameter equals to "My Parameter"     } } 

Top 3 video Explaining c# - ThreadStart with parameters

Related QUESTION?