vote buttons
1
1
beginner
0
intermediate
0
advanced
15-Oct-2014 04:37 UTC
Charlie
82

1 Answers

vote buttons
2

1. Pass data using Lambda Expressions:

static void Main()
{
  String m = "yeahh!";
  Thread thread = new Thread ( () => PrintToConsole (m) );
  thread.Start();
}
 
static void PrintToConsole (string message) 
{
  Console.WriteLine (message);
}


In the above example we have effectively passed m into the thread function. Any number of parameters can be passed this way.

2. Another way is to use the overloaded Thread.Start function which accepts ParamterizedThreadStart.

string parameter = "xyz";
Thread thread = new Thread(new ParameterizedThreadStart(PrintToConsole));
thread.Start(parameter);
private void PrintToConsole(object o)
{
  String m = (String) o;
  Console.WriteLine(m);
}

3. This is the same as (1) but the example is for .Net 4.0 Tasks

Task.Factory.StartNew(() => SomeMethod(p1,p2,p3));
15-Oct-2014 04:51 UTC
Charlie
82