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的做到這一點,我想明白它。我如何獲得一個線程通知另一個線程它需要做些什麼?