Monday, May 16, 2016

How do you pass arguments to a Thread that you create

1. Pass data using Lambda Expressions:
  1. static void Main()
  2. {
  3. String m = "yeahh!";
  4. Thread thread = new Thread ( () => PrintToConsole (m) );
  5. thread.Start();
  6. }
  7. static void PrintToConsole (string message)
  8. {
  9. Console.WriteLine (message);
  10. }

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.

  1. string parameter = "xyz";
  2. Thread thread = new Thread(new ParameterizedThreadStart(PrintToConsole));
  3. thread.Start(parameter);
  4. private void PrintToConsole(object o)
  5. {
  6. String m = (String) o;
  7. Console.WriteLine(m);
  8. }

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

  1. Task.Factory.StartNew(() => SomeMethod(p1,p2,p3));

No comments:

Post a Comment

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code