Threads
最早的版本,微软推荐不要再使用Thread了
thread不支持带返回值的方法
本身也没有线程回调,但是可以自己做一个
private void btnThreads_Click(object sender, EventArgs e) { Stopwatch watch = new Stopwatch(); watch.Start(); Console.WriteLine(); Console.WriteLine("********************btnThread_Click Start 主线程id={0}********************", Thread.CurrentThread.ManagedThreadId); List<Thread> threadList = new List<Thread>(); for (int i = 0; i < 5; i++) { ParameterizedThreadStart method = o => TestThreadWithoutReturn(o.ToString()); Thread thread = new Thread(method);//1. 默认前台线程:程序退出后,计算任务会继续 thread.IsBackground = true;//2. 后台线程:程序退出,计算理解结束 thread.Start(string.Format("btnThread_Click_{0}", i)); threadList.Add(thread); } //for (int i = 0; i < 5; i++) //{ // //使用Thread完成多线程回调 // int b = i; // ParameterizedThreadStart method = o => TestThreadWithoutReturn(o.ToString());//要多线程执行的任务 // Action callback = () => Console.WriteLine("回调 btnAsync_Click_{0}",b);//回调执行的任务 // ThreadStart methodAll = new ThreadStart(() => // { // method.Invoke(string.Format("btnAsync_Click_{0}", b)); // callback.Invoke(); // }); // Thread thread = new Thread(methodAll); // thread.Start(); // threadList.Add(thread); //} foreach (var item in threadList ) { item.Join(); //主线程等待 } watch.Stop(); Console.WriteLine("********************btnThread_Click End 主线程id={0} {1}********************", Thread.CurrentThread.ManagedThreadId, watch.ElapsedMilliseconds); Console.WriteLine(); }
private void TestThreadWithoutReturn(string name) { Console.WriteLine("TestThread Start Name={2},当前线程的id:{0},当前时间为{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("hh:mm:ss:fff"), name); long Sum = 0; for (int i = 1; i < 999999999; i++) { Sum += i; } //Thread.Sleep(2000); Console.WriteLine("TestThread End Name={2},当前线程的id:{0},当前时间为{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("hh:mm:ss:fff"), name); }