0

Is it possible to pass a parameter inside threadstart to start execution of the method?

int value = 123;
Thread t = new Thread(new ThreadStart(fail.DoWork(value)));


Class fail
{
  public void DoWork(int Value)
}

How else can I pass this parameter inside DoWork?

user759913
  • 41
  • 1
  • 8

4 Answers4

2

You can try

 int value = 123;
 fail objfail = new fail();
 var t = new Thread(() => objfail.DoWork(value));
 t.Start();
pravprab
  • 2,301
  • 3
  • 26
  • 43
1

You need ParameterizedThreadStart in this case:

void Main()
{
    Fail fail = new Fail();
    int value = 123;
    Thread t = new Thread(fail.DoWork); // same as: new Thread(new ParameterizedThreadStart(fail.DoWork));
    t.Start(value);
}

public class Fail
{
  public void DoWork(object value)
  {
    Console.WriteLine("value: {0}", value);
  }
}
Wagner DosAnjos
  • 6,304
  • 1
  • 15
  • 29
0

I BELIEVE you can also do with lambda expession something like...

Thread t = new Thread(new ThreadStart( () => fail.DoWork(value)));

It took me a while to wrap my head around lambda, but basically what is happening in the above line is this.

Call a function that has no parameters (as a normal call might have). This is represented by the (). The actual definition of the function is what follows the => which does your call with the parameter. This is the same as if you had done the following.

currentMethodStartingTheThread()
{
   Thread t = new Thread(new ThreadStart( CallAsParameterized() );
}

void CallAsParameterized()
{
   int value = 123;
   fail.DoWork(value);
}


Class fail
{
  public void DoWork(int Value)
  { do whatever with the parameter value )
}

The only real difference via lambda expression is you do not have to explicitly write the wrapper function with the parameter.

DRapp
  • 47,638
  • 12
  • 72
  • 142
0

I prefer this syntax:

int value = 123;
var t = new Thread((ThreadStart)(() => fail.DoWork(value)));
t.Start();
Enigmativity
  • 113,464
  • 11
  • 89
  • 172