NET多線程探索-NET線程基礎知識點
2012-03-19 13:40 海不是藍 閱讀(703) 評論(0) 收藏 舉報前臺線程和后臺線程
前臺線程:當應用程序結束的時候,前臺線程如果沒有完成任務,那么前臺線程就不會結束。除非你強行結束應用程序進程中所有前臺線程。前臺線程適合必須執行完的任務。
后臺線程:當應用程序結束的時候后臺線程會被CLR強行結束,不會拋出異常。示例:
static void Main(string[] args) { Thread t = new Thread(Test); t.IsBackground = true; //這里線程是后臺線程,應用程序馬上結束 //假如是前臺線程,大約5秒以后結束 t.Start(); Console.WriteLine("A"); } static void Test() { Thread.Sleep(5 * 1000); Console.WriteLine("B"); }
判斷線程是否結束
public bool IsAlive { get; } public void Join();
static void Main(string[] args) { Thread A = new Thread(() => { Thread.Sleep(2 * 1000); }); Thread B = new Thread(() => { Thread.Sleep(3 * 1000); }); A.Start(); B.Start(); while (A.IsAlive) { Console.WriteLine("線程A正在執行..."); Thread.Sleep(500); } Console.WriteLine("線程A執行完畢..."); //這個是阻塞方法,直到線程B完成才能執行后面的代碼 B.Join(); Console.WriteLine("線程B執行完畢..."); Console.Read(); }
為線程傳遞參數
public delegate void ParameterizedThreadStart(object obj); [SecuritySafeCritical] public Thread(ParameterizedThreadStart start);
static void Main(string[] args) { Thread A = new Thread((object str) => { Thread.Sleep(1 * 1000); Console.WriteLine(str); }); A.Start("A Thread..."); A.Join();//阻塞程序直到A線程執行完畢 Thread B = new Thread(new ParameterizedThreadStart((object str) => { Thread.Sleep(1 * 1000); Console.WriteLine(str); })); B.Start("B Thread..."); B.Join(); Thread C = new Thread(new ParameterizedThreadStart(Test)); C.Start("C Thread..."); Console.Read(); } static void Test(object str) { Thread.Sleep(1 * 1000); Console.WriteLine(str); }
線程優先等級
優先等級高的線程占用更多的CUP時間。
但是當優先等級高的線程正在等待一些資源的時候,優先等級低的線程可以運行。
public class MyThread { //執行計數 public Int32 Count; //執行開關 public static bool Stop; //執行線程 public Thread t; public MyThread(string ThreadName) { //設置開關 Stop = false; //設置線程方法 t = new Thread(new ThreadStart(() => { while (!Stop && Count < 10000000) { Count++; } Stop = true; Console.WriteLine("{0}線程結束...", t.Name); })); //設置線程名字 t.Name = ThreadName; } }
static void Main(string[] args) { MyThread A = new MyThread("Hige A"); MyThread B = new MyThread("Low B"); A.t.Priority = ThreadPriority.Highest; B.t.Priority = ThreadPriority.Lowest; A.t.Start(); B.t.Start(); A.t.Join(); B.t.Join(); Console.WriteLine("A線程計數{0}", A.Count); Console.WriteLine("B線程計數{0}", B.Count); Console.Read(); }
線程池
注意幾點: 1.托管線程池中的線程都是后臺線程, 2.當需求比較少時,線程池線程的實際數量可以低于這些最小值。
線程池的優點:創建線程和銷毀線程都是需要消耗比較多的系統資源,而線程池始終維護著一個線程列表,當線程處于空閑的時候只是休眠,
一旦有任務進來就會被喚醒執行任務。
static void Main(string[] args) { ThreadPool.QueueUserWorkItem((object str) => { Thread.Sleep(1 * 1000); Console.WriteLine(str); }, "Hello"); int max, min, io; ThreadPool.GetMaxThreads(out max, out io); Console.WriteLine("線程池中輔助線程的最大數目:{0},\n線程池中異步 I/O 線程的最大數目{1}", max, io); ThreadPool.GetMinThreads(out min, out io); Console.WriteLine("線程池根據需要創建的最少數量的輔助線程:{0},\n線程池根據需要創建的最少數量的異步 I/O 線程{1}", min, io); Console.Read(); }
線程池適合一些簡單的任務,如果對任務線程需要比較全的控制權限,那么就自己單獨聲明線程。

浙公網安備 33010602011771號