我还在计划阶段,所以我没有完整的代码来显示。但是我很好奇如果想要在不同程序集之间同步线程,将如何使用manualresetevent。例如,我在执行task1()的assembly1中编写了classA。接下来,我在Assembly2中创建另一个classB,创建一个线程来运行classA.task1()。我想让classB等到classA完成。重要的是(我们假设)我在一个单独的线程上运行它。总之,一个代码片段看起来像:我可以在程序集之间使用ManualResetEvent吗?
Assembly2.ClassB:
private void main() { // for brevity
Thread newThread = new Thread(new ThreadStart(assembly1.classA.task));
newThread.Start();
// Wait until some process in classA.task() is done
if(classA.mySocket.Connected) {
// this may never occur because task1() didn't complete it's job
}
// do the rest
}
Assembly1.ClassA
public Socket mySocket;
public void task1() {
// must stop all other threads until these lines have
// been processed
// create socket, and connect to remote endpoint
// Ok, to signal other threads to continue.
startReceiving();
}
private void startReceiving() {
while(IsValid) {
mySocket.Receive(); //
}
}
我需要在这两个类创建ManualResetEvents?这如何工作?
谢谢!
编辑: 我已经更新的代码更有效的例子,请不要介意语法,我只是想传达出的主意。
您应该只需要创建在B中的一个手动重置事件。在新线程上调用task1并等待它结束 – tam