C#子線程執(zhí)行完后通知主線程的方法
其實這個比較簡單,子線程怎么通知主線程,就是讓子線程做完了自己的事兒就去干主線程的轉回去干主線程的事兒。
那么怎么讓子線程去做主線程的事兒呢,我們只需要把主線程的方法傳遞給子線程就行了,那么傳遞方法就很簡單了委托傳值嘛;
下面有一個例子,子線程干一件事情,做完了通知主線程
public class Program { //定義一個為委托 public delegate void Entrust(string str); static void Main(string[] args) { Entrust callback = new Entrust(CallBack); //把方法賦值給委托 Thread th = new Thread(Fun); th.IsBackground = true; th.Start(callback);//將委托傳遞到子線程中 Console.ReadKey(); } private static void Fun(object obj) { //注意:線程的參數(shù)是object類型 for (int i = 1; i <= 10; i++) { Console.WriteLine("子線程循環(huán)操作第 {0} 次",i); Thread.Sleep(500); } Entrust callback = obj as Entrust;//強轉為委托 callback("我是子線程,我執(zhí)行完畢了,通知主線程"); //子線程的循環(huán)執(zhí)行完了就執(zhí)行主線程的方法 } //主線程的方法 private static void CallBack(string str) { Console.WriteLine(str); } }
上面就是一個通過委托進行向主線程傳值(也就是通知主線程)的過程,上面我們是自己定義了一個委托,當然我們也可以使用.NET為我們提供的Action<>和Fun<>泛型委托來處理,就像這樣
public class Program { //定義一個為委托 public delegate void Entrust(string str); static void Main(string[] args) { Action<string> callback = ((string str) => { Console.WriteLine(str); }); //Lamuda表達式 Thread th = new Thread(Fun); th.IsBackground = true; th.Start(callback); Console.ReadKey(); } private static void Fun(object obj) { for (int i = 1; i <= 10; i++) { Console.WriteLine("子線程循環(huán)操作第 {0} 次",i); Thread.Sleep(500); } Action<string> callback = obj as Action<string>; callback("我是子線程,我執(zhí)行完畢了,通知主線程"); } } //上面的Lamuda表達式也可以回城匿名函數(shù) //Action<string> callback = delegate(string str) { Console.WriteLine(str); };
下面是運行結果
以上這篇C#子線程執(zhí)行完后通知主線程的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Unity實戰(zhàn)之FlyPin(見縫插針)小游戲的實現(xiàn)
這篇文章主要介紹了利用Unity制作FlyPin(見縫插針)小游戲的實現(xiàn)方法,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起試一試2022-01-01C#使用WebService結合jQuery實現(xiàn)無刷新翻頁的方法
這篇文章主要介紹了C#使用WebService結合jQuery實現(xiàn)無刷新翻頁的方法,涉及C#中WebService與jQuery操作的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04