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));
No comments:
Post a Comment