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

标签 c# multithreading

我还处于计划阶段,所以我没有完整的代码可以展示。但是我很好奇,如果您想在不同的程序集之间同步线程,将如何使用 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/

相关文章:

java - catalina.out 中的这些警告是什么?

c# - 将 <img> HTML 标签添加到 C# 字符串

c# - 访问 BindingContext[dataSource] 与 BindingContext[dataSource, dataMember] 有什么不同?

c# - 在 IDisposable 对象上使用语句 - 调用 Dispose 方法的延迟

multithreading - 并发(多线程)程序挂起,除非我打印出一些东西

python - Python 会在线程模式下使用所有处理器吗?

c# - 在线程应用程序中使用 C# Volatile 关键字

java - Spring MVC Scoped Bean 依赖和竞争条件

c# - 正则表达式匹配括号和大括号

c# - .Net Logger(编写自己的 vs log4net/enterprise logger/nlog 等)