gpt4 book ai didi

c# - 我可以跨程序集使用 ManualResetEvent 吗?

转载 作者:太空宇宙 更新时间:2023-11-03 22:10:34 26 4
gpt4 key购买 nike

我还处于计划阶段,所以我没有完整的代码可以展示。但是我很好奇,如果您想在不同的程序集之间同步线程,将如何使用 manualresetevent。例如,我在 assembly1 中编写了执行 task1() 的 classA。接下来,我在 Assembly2 中有另一个 classB,我在其中创建了一个线程来运行 classA.task1()。我想让 classB 等到 classA 完成。重要的是(让我们假设)我在一个单独的线程上运行它。简而言之,一段代码如下所示:

程序集 2.B 类:

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
}

程序集 1.A 类

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 吗?这怎么行?

谢谢!

编辑:我已经更新了代码以获得更有效的示例,请不要介意语法,我只是想传达这个想法。

最佳答案

是的,这很好,但是您需要在两个对象之间共享 ManualResetEvent 的实例。您可以通过 Thread 上的构造函数传递此共享实例,该构造函数采用 ParameterizedThreadStart

但是,如果您所做的只是等待 newThread 完成,只需使用 Thread.Join :

newThread.Start();
newThread.Join();

关于c# - 我可以跨程序集使用 ManualResetEvent 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6785179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com