2014-05-21 48 views
0

我對代表相對較新,但仍然覺得有些困惑。我想要實現它們的方式需要從一個線程調用一個委託給另一個線程。哪個線程將執行該方法?我會寫一些示例代碼在這裏:委託和線程 - 哪個線程管理被調用的方法?

public delegate void MyDel();  

    public class main() 
    { 

     Object MyLock = new Object();    
     public volatile int NumRegistered = 0; 
     public volatile MyDel Invoker = new MyDel; 


     public main() 

     { 
      Thread t1 = new Thread(new ThreadStart(ThreadA)); 
      Thread t2 = new Thread(new ThreadStart(ThreadB)); 

      t1.Start(); 
      t2.Start(); 

      while(true) 
      { 
       if(int == 2) 
       { 
        Invoker(); 
        int = 1; 
       } 
      } 
     } 

     public void ThreadA() 
     { 
      MyFirstThread tA = new MyFirstThread(this);    
     } 

     public void ThreadB() 
     { 
      MySecondThread tB = new MySecondThread(this); 
     } 

     public class MyFirstThread 
     {   
      public MyFirstThread(main MyParent) 
      { 
       lock(MyParent.MyLock) 
       { 
        MyParent.Invoker += new MyDel(MethodA); 
        MyParent.NumRegistered++; 
       } 

       while(true) 
       { 
        //do something 
       }     
      } 

      public void MethodA() 
      { 
       //This Method A - What thread will run it? The "Main" thread or "t1"? 
      } 
     } 

     public class MySecondThread 
     { 

      public MySecondThread(main MyParent) 
      { 
       lock(MyParent.MyLock) 
       { 
        MyParent.Invoker += new MyDel(MethodB); 
        MyParent.NumRegistered++; 
       } 

       while(true) 
       { 
        //do something 
       }    
      } 

      public void MethodB() 
      { 
       //This Method B - what thread will run it? The "Main" thread or "t2"? 
      }    
     } 
    } 

基本上我只是想學寫一個多線程的回調「註冊表」,而不使用BackgroundWorker類,因爲我已經可以用BackgroundWorker的做到這一點,我想明白它。我如何獲得一個線程通知另一個線程它需要做些什麼?

回答

1

因此,您的兩個新線程永遠不會執行MethodAMethodB beucase,它們永遠不會調用委託。他們正在定義將要執行的方法,他們從未真正執行該委託。主線程是實際嘗試調用委託的唯一線程,因此它在主線程中運行。