其實這個比較簡單,子線程怎么通知主線程,就是讓子線程做完了自己的事兒就去干主線程的轉回去干主線程的事兒。
那么怎么讓子線程去做主線程的事兒呢,我們只需要把主線程的方法傳遞給子線程就行了,那么傳遞方法就很簡單了委托傳值嘛;
下面有一個例子,子線程干一件事情,做完了通知主線程
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) {      //注意:線程的參數是object類型      for (int i = 1; i <= 10; i++)      {        Console.WriteLine("子線程循環操作第 {0} 次",i);        Thread.Sleep(500);      }      Entrust callback = obj as Entrust;//強轉為委托      callback("我是子線程,我執行完畢了,通知主線程");      //子線程的循環執行完了就執行主線程的方法    }    //主線程的方法    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("子線程循環操作第 {0} 次",i);        Thread.Sleep(500);      }      Action<string> callback = obj as Action<string>;      callback("我是子線程,我執行完畢了,通知主線程");    }  } //上面的Lamuda表達式也可以回城匿名函數 //Action<string> callback = delegate(string str) { Console.WriteLine(str); };下面是運行結果

以上這篇C#子線程執行完后通知主線程的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答