【问题标题】:how to Block a method until another method executes in c# .net [closed]如何阻止一个方法,直到另一个方法在c#.net中执行[关闭]
【发布时间】:2014-10-09 06:28:38
【问题描述】:

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

【问题讨论】:

    标签: c# .net multithreading thread-synchronization


    【解决方案1】:

    这称为信号,实现它的最简单方法是通过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.");
    

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多