.net中创建多线程可以有四种方式:
Thread类、委托、ThreadPool类、Task类
- Thread类创建多线程
/// <summary> /// Thread类启动 /// </summary> public static void Thread_Start() { Thread thread = new Thread(new ParameterizedThreadStart(AddA)); thread.Start("Thread"); }
- 委托方式创建多线程
delegate void Delegate_Add(Object stateInfo); /// <summary> /// 委托方式启动 /// </summary> public static void Delegate_Start() { Delegate_Add dele_add = AddA; dele_add.BeginInvoke("Delegate", null,null); }
- ThreadPool类创建多线程
/// <summary> /// 线程池方式启动 /// </summary> public static void ThreadPool_Start() { WaitCallback w = new WaitCallback(AddA); ThreadPool.QueueUserWorkItem(w,"ThreadPool"); }
- Task类创建多线程
/// <summary> /// Task方式启动 /// </summary> public static void Task_Start() { Action<object> add_Action = AddA; Task task = new Task(add_Action, "Task"); task.Start(); }
- IsBackground
所有的多线程操作,必定有一个主线程,主线程(ParentThread)与子线程(ChildThread)的生命周期也是相互作用的,
子线程中的IsBackground属性,决定了两类线程生命周期的依赖关系。
如果ChildThread.IsBackGround=true,ParentThread结束时,ChildThread也会终止;
如果ChildThread.IsBackGround=false,ParentThread必须等ChildThread终止后才会终止。
对于这四种多线程方法,默认生成线程的IsBackGround有所不同:
类型 | IsBackGround |
Thread类 | false |
委托 | true |
ThreadPool类 | true |
Task类 | true |
辅助方法
public static int a; static void Main(string[] args) { MultiThreadDemo demo = new MultiThreadDemo(); Console.WriteLine("Main Thread ID:" + Thread.CurrentThread.ManagedThreadId); MultiThreadTest(); Thread.Sleep(10000); Console.WriteLine("a:" + a); Console.WriteLine("Main thread exits."); } /// <summary> /// 打印当前线程信息 /// </summary> public static void PrinctCurrentThreadInfo() { var t = Thread.CurrentThread; Console.WriteLine("Current Thread ID:" + t.ManagedThreadId); Console.WriteLine("Is Back Ground:{0}", t.IsBackground); Console.WriteLine("Thread Priority:" + t.Priority.ToString()); Console.WriteLine("Thread State:" + t.ThreadState.ToString()); } /// <summary> /// 测试方法 /// </summary> /// <param name="stateInfo"></param> public static void AddA(Object stateInfo) { Console.WriteLine("{0,-20} Thread ID:{1}", stateInfo.ToString(), Thread.CurrentThread.ManagedThreadId); Console.WriteLine("IsBackground:{0} ", Thread.CurrentThread.IsBackground); while (a < 10) { Console.WriteLine("{0,-20} Start :{1}", stateInfo.ToString(), a); Thread.Sleep(10); a++; Console.WriteLine("{0,-20} End :{1} ", stateInfo.ToString(), a); } Console.WriteLine("{0,-20} Thread ID:{1} Result:{2}", stateInfo.ToString(), Thread.CurrentThread.ManagedThreadId, a); return; } /// <summary> /// 多线程测试 /// </summary> public static void MultiThreadTest() { a = 0; Thread_Start(); Delegate_Start(); ThreadPool_Start(); Task_Start(); }