1 Thread 默认为前台线程,即主程序退出后,线程还可以继续(曾经就掉入这个坑中,使用两线程分别进行UDP收发,结果发线程结束了退出方法,收线程还在继续)
2 Thread 没有可以暂停,可以重新启动,但是没有结束方法,使用Abort()方法强制销毁会抛异常。
3 线程的等待用Join()实现
List<Thread> threadList = new List<Thread>(); for (int i = 0; i < 5; i++) { string name = string.Format("btnThread_Click_{0}", i); ThreadStart method = () => this.TestThread(name); Thread thread = new Thread(method);//1 默认前台线程:程序退出后,计算任务会继续 thread.IsBackground = true;//2 后台线程:程序退出,计算立即结束 thread.Start(); threadList.Add(thread); //ParameterizedThreadStart method = o => this.TestThread(o.ToString()); //Thread thread = new Thread(method); //thread.Start(name); } foreach (Thread thread in threadList) { thread.Join(); }
4 Thread 也没有回调和返回值,如果使用回调函数,需要手动实现
/// <summary> /// 使用Thread 完成多线程回调 /// </summary> /// <param name="method">要多线程执行的任务</param> /// <param name="callback">回调执行的任务</param> private void ThreadBeginInvoke(ThreadStart method, Action callback) { ThreadStart methodAll = new ThreadStart(() => { method.Invoke(); callback.Invoke(); }); Thread thread = new Thread(methodAll); thread.Start(); }