如今C#已經建議擯棄使用 Suspend, Resume 暫停/恢復線程, 也儘可能少用 Abort方法中斷一個線程.函數
建議使用線程的同步手段有: Mutex、ManualResetEvent、AutoResetEvent, Monitor.oop
下面再對此進行詳細描述.this
Thread類的構造函數有2類:spa
一種是不帶參數(ThreadStart 委託) --線程
public Thread(ThreadStart start);
另外一種是帶參數(ParameterizedThreadStart 委託) --code
public Thread(ParameterizedThreadStart start);
ParameterizedThreadStart 委託簽名:blog
public delegate void ParameterizedThreadStart(Object obj);
示例:進程
1. 不帶參數:同步
// 定義線程方法: private static void ThreadMain() { Console.WriteLine("This is other thread main method."); } // 調用: Thread mythread = new Thread(ThreadMain); mythread.Start();
2. 帶參數:string
// 定義線程方法: private static void MainThreadWithParameters(object o) { Data d = (Data)o; //類型轉換 Console.WriteLine("Running in a thread, received {0}", d.Message); } public struct Data { public string Message; } // 調用: var data = new Data { Message = "Info" }; Thread t2 = new Thread(MainThreadWithParameters); t2.Start(data); // 傳入參數
3. 經過定義類傳遞參數:
// 定義存放數據和線程方法的類: public class MyThread { private string message; public MyThread(string data) { this.message = data; } public void ThreadMethod() { Console.WriteLine("Running in a thread, data: {0}", this.message); } } // 調用 var obj = new MyThread("info"); Thread myThread = new Thread(obj.ThreadMethod); //ThreadStart 委託 mythread.Start();
C#中,Thread類有一個IsBackground 的屬性.MSDN上對它的解釋是:獲取或設置一個值,該值指示某個線程是否爲後臺線程。
.Net中的線程,能夠分爲後臺線程和前臺線程。後臺線程與前臺線程並無本質的區別,它們之間惟一的區別就是:後臺線程不會防止應用程序的進程被終止掉。就是當前臺線程都結束了的時候,整個程序也就結束了,即便還有後臺線程正在運行,此時,全部剩餘的後臺線程都會被中止且不會完成.可是,只要還有一個前臺線程沒有結束,那麼它將阻止程序結束.應用程序進程的存亡由前臺線程決定而於後臺線程無關.這就是它們的區別.改變線程從前臺到後臺不會以任何方式改變它在CPU協調程序中的優先級和狀態。由於前臺後線程與程序進程的優先級無關.下面的代碼示例對比了前臺線程與後臺線程的行爲。建立一個前臺線程和一個後臺線程。前臺線程使進程保持運行,直到它完成它的 while 循環。前臺線程完成後,進程在後臺線程完成它的 while 循環以前終止。
using System; using System.Threading; class Test { static void Main() { BackgroundTest shortTest = new BackgroundTest(10); Thread foregroundThread = new Thread(new ThreadStart(shortTest.RunLoop)); foregroundThread.Name = "ForegroundThread"; BackgroundTest longTest = new BackgroundTest(50); Thread backgroundThread = new Thread(new ThreadStart(longTest.RunLoop)); backgroundThread.Name = "BackgroundThread"; backgroundThread.IsBackground = true; foregroundThread.Start(); backgroundThread.Start(); } } class BackgroundTest { int maxIterations; public BackgroundTest(int maxIterations) { this.maxIterations = maxIterations; } public void RunLoop() { String threadName = Thread.CurrentThread.Name; for(int i = 0; i < maxIterations; i++) { Console.WriteLine("{0} count: {1}", threadName, i.ToString()); Thread.Sleep(250); } Console.WriteLine("{0} finished counting.", threadName); } }