在上一遍文章中講到多線程基礎,在此篇文章中咱們來學習C#裏面Thread類。Thread類是在.net framework1.0版本中推出的API。若是對線程的概念還不太清楚的小夥伴請閱讀個人上一遍文章:多線程系列(一),多線程基礎html
在本篇文章中新開啓一個線程來異步調用的方法代碼爲:多線程
private void DoSomeThing(string btnName) { Console.WriteLine($"{btnName} 開始,當前線程id:{Thread.CurrentThread.ManagedThreadId}"); long lResult = 0; for (long i = 0; i < 1_00_000_000; i++) { lResult += i; } Console.WriteLine($"{btnName} 結束,當前線程id:{Thread.CurrentThread.ManagedThreadId}"); }
方式一:基於委託ParameterizedThreadStart異步
ParameterizedThreadStart method = o => this.DoSomeThing("btnThread_Click"); Thread thread = new Thread(method); thread.Start();//開啓線程,執行委託的內容
方式二:基於委託ThreadStart函數
ThreadStart method = () => { Thread.Sleep(3000); this.DoSomeThing("btnThread_Click"); }; Thread thread = new Thread(method); thread.Start();//開啓線程,執行委託的內容
thread.Suspend();//暫停,掛起線程,若是線程已經掛起,則不起做用學習
thread.Resume();//繼續已經掛起的線程測試
thread.Abort();//終止線程,會在當前線程中拋出一個異常引起線程中止,不過會有延遲,由於線程屬於計算機資源,程序想停下線程,只能向操做系統通知(拋異常),不必定真的能停下來this
Thread.ResetAbort();//終止當前線程,取消當前線程的全部請求,只能終止一次spa
Thread.Sleep();//使當前線程休眠多少毫秒再繼續執行操作系統
方式一:經過thread.ThreadState獲取當前線程的狀態.net
while (thread.ThreadState != System.Threading.ThreadState.Stopped) { Thread.Sleep(500); Console.WriteLine($"線程_{ thread.ManagedThreadId.ToString("00")}_正在運行中..."); }
方式二:經過Join等待
thread.Join(); //等待線程thread執行完畢
thread.Join(5000); //限時等待,最多等待5000毫秒
thread.Priority = ThreadPriority.Highest;
設置線程的優先級爲最高優先級:優先執行,但不表明優先完成,甚至說極端狀況下,還有意外發生,不能經過這個來控制線程的執行前後順序
thread.IsBackground = false;//默認是false 前臺線程,進程關閉,線程須要計算完後才退出
thread.IsBackground = true; //關閉進程,線程退出
咱們但願某個線程在執行某個動做以後觸發另外一個動做,下面是我基於Thread封裝的線程回調函數
/// <summary> /// 基於thread封裝一個回調,啓動子線程執行動做A--不阻塞--A執行完後子線程會執行動做B,不阻塞 /// </summary> /// <param name="method">動做A</param> /// <param name="action">動做B</param> private void ThreadWithCallBack(ThreadStart method,Action action) { ThreadStart threadStart = () => { method.Invoke(); action.Invoke(); }; new Thread(threadStart).Start(); }
調用測試代碼:
ThreadStart method = () => { this.DoSomeThing("btnThread_Click"); }; Action actionCallBack = () => { Console.WriteLine("method 的回調"); }; this.ThreadWithCallBack(method, actionCallBack);
下面是我基於Thread封裝的獲取子線程的返回值函數
T t = default(T); ThreadStart threadStart = () => { t = func.Invoke(); }; Thread thread = new Thread(threadStart); thread.Start(); return new Func<T>(() => { thread.Join(); return t; });
調用測試代碼
Func<int> func = () => { return DateTime.Now.Hour; }; Func<int> funcThread = this.ThreadWithReturn<int>(func);//非阻塞 int res = funcThread.Invoke();//阻塞
在下一篇中,會繼續講到線程池