ThreadStart 与ParameterizedThreadStart的区别
1) ParameterizedThreadStart与ThreadStart
1 static void Main(string[] args) 2 { 3 4 #region ParameterizedThreadStart第一种写法 5 Thread thread = new Thread(new ParameterizedThreadStart( 6 (s) => { 7 8 Console.WriteLine(s.ToString()); 9 } 10 11 )); 12 thread.Start("45 1"); 13 #endregion 14 #region ParameterizedThreadStart第二种写法 15 //把方法抽出WriteOut 16 ParameterizedThreadStart parThread = new ParameterizedThreadStart(WriteOut);//WriteOut是方法 17 Thread thread2 = new Thread(parThread); 18 thread2.Start("3433343 2"); 19 20 #endregion 21 22 #region ThreadStart第一种写法 23 24 Thread thread3 = new Thread(new ThreadStart( 25 () => 26 { 27 28 Console.WriteLine("ThreadStart里是没有参数的方法 3"); 29 } 30 31 )); 32 thread3.Start();//no parameter 33 #endregion 34 35 #region ThreadStart第2种写法 36 37 Thread thread4 = new Thread( 38 () => 39 { 40 41 Console.WriteLine("ThreadStart里是没有参数的方法222 4"); 42 } 43 44 ); 45 thread4.Start();//no parameter 46 #endregion 47 Console.ReadKey(); 48 49 } 50 51 private static void WriteOut(object obj) 52 { 53 Console.WriteLine(obj.ToString()); 54 }
输出结果顺序是不定的。
等等
2)ParameterizedThreadStart多个参数的传递
可以把多个值封装到一个类里进行传递
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 6 ParameterizedThreadStart paraThread = new ParameterizedThreadStart(AddTwoNumber); 7 Thread thread = new Thread(paraThread); 8 Number numbers = new Number(); 9 numbers.SetPare(1, 2); 10 11 12 thread.Start(numbers); 13 Console.ReadKey(); 14 15 } 16 17 private static void AddTwoNumber(object obj) 18 {//这里传过来一个类 19 if (obj is Number) 20 { 21 Number num = (Number)obj; 22 Console.WriteLine(num.First + " +" + num.Second+"=" +(num.First+num.Second)); 23 } 24 } 25 26 } 27 28 class Number 29 { 30 private int first; 31 private int second; 32 public int First 33 { 34 35 get 36 { return first;} 37 38 set 39 { first = value;} 40 41 } 42 public int Second 43 { 44 get { return second; } 45 set { second = value; } 46 } 47 48 public void SetPare(int n, int m) 49 { 50 first = n; 51 second = m; 52 } 53 54 }