给线程传递参数.
1 public class ThreadWithState { 2 //要传递的参数. 3 private string boilerplate; 4 private int value; 5 //通过构造函数传递参数. 6 public ThreadWithState(string text, int number) { 7 boilerplate = text; 8 value = number; 9 } 10 //给线程执行的方法,本处返回类型为void是为了能让ThreadStart来直接调用. 11 public void ThreadProc() { 12 //要执行的任务,本处只显示一下传入的参数 13 Console.WriteLine(boilerplate, value); 14 } 15 } 16 17 public class Example { 18 public static void Main() { 19 //实例化ThreadWithState类,为线程提供参数 20 ThreadWithState tws = new ThreadWithState( 21 "This report displays the number {0}.", 42); 22 // 创建执行任务的线程,并执行 23 Thread t = new Thread(new ThreadStart(tws.ThreadProc)); 24 t.Start(); 25 Console.WriteLine("Main thread does some work, then waits."); 26 t.Join(); 27 Console.WriteLine( 28 "Independent task has completed; main thread ends."); 29 } 30 }