BackgroundWorker:线程执行完毕之后我们可以继续一些操作
示例:
class Program { static void Main(string[] args) { Console.WriteLine("Main(string[] args)方法中:当前执行的线程编号:{0}", Thread.CurrentThread.ManagedThreadId); //BackgroundWorker //创建一个后台执行者对象 BackgroundWorker backWorker = new BackgroundWorker(); //设置该对象要在后台执行的方法 backWorker.DoWork += new DoWorkEventHandler(backWorker_DoWork); //设置另外一个事件:当程序执行完毕后触发的事件 backWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backWorker_RunWorkerCompleted); //开始执行 backWorker.RunWorkerAsync(new int[] { 1, 100 }); Console.WriteLine("主线程继续......."); Console.ReadKey(); } //当后台方法执行完毕后触发的事件 static void backWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { Console.WriteLine("backWorker_RunWorkerCompleted方法中:当前执行的线程编号:{0}", Thread.CurrentThread.ManagedThreadId); Console.WriteLine("最后输出结果是:{0}", e.Result); } //要在后台执行的方法 static void backWorker_DoWork(object sender, DoWorkEventArgs e) { Console.WriteLine("backWorker_DoWork方法中:当前执行的线程编号:{0}", Thread.CurrentThread.ManagedThreadId); if (e.Argument != null) { int[] arr = e.Argument as int[]; //把方法调用完毕后的值赋值给e.Result e.Result = Sum(arr[0], arr[1]); } } static int Sum(int from, int to) { int sum = 0; for (int i = from; i <= to; i++) { sum += i; } return sum; } }