c# - 如何在 c# .net 中阻止一个方法直到另一个方法执行

标签 c# .net multithreading thread-synchronization

<分区>

我有一个应用程序,我在其中向硬件 Controller 发送命令,然后 Controller 响应该命令。在这里,我有一个命令队列,我一个一个地发送它们,现在我想同步发送所有命令,这意味着当我收到第一个命令响应时,我只会发送下一个命令。 我有两种方法,一种用于发送命令,另一种用于处理接收到的命令。

最佳答案

这称为信号,实现它的最简单方法是通过 ManualResetEvent

如果您在 ManualResetEvent 对象上调用 WaitOne,当前线程将被阻塞,直到另一个线程通过调用 Set 发出“信号”让其继续在同一个对象上:

var signal = new ManualResetEvent(false); // instantiate in "unsignaled" state

new Thread (() =>
{
    Console.WriteLine("Sending command to hardware controller...");

    // send your command
    // ...

    Console.WriteLine("Done.");
    signal.Set(); // signal the waiting thread that it can continue.
}).Start();

Console.WriteLine("Waiting for hardware thread to do it's work...");
signal.WaitOne(); // block thread until we are signaled.
signal.Dispose();
Console.WriteLine("Got our signal! we can continue.");

关于c# - 如何在 c# .net 中阻止一个方法直到另一个方法执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26271714/

相关文章:

c# - 锁定文本框中的有效字符

c# - 四边形找形算法

c# - ADO.Net SQLCommand.ExecuteReader() 变慢或挂起

.net - 在调试中可视化列表(或打印到即时窗口)

c# - GOTO 是退出双 Foreach 的唯一方法吗?

java - 如何并行而不是顺序执行多个查询?

c# - 如何将数据 Controller 发送到 View

.net - 托管/非托管 C++ 中的 wchar_t NUL

c++ - C++ 11:将 vector 元素作为线程传递到线程函数中

c++ - 如何在Qt中取消暂停线程