0

我有一个简单的应用程序来说明CountdownEvent。很好,但我想以某种方式设置WaitHandleCountDownEvent使用它。可能吗?如何做到这一点?我想我应该注册WaitHandle并将其传递给CountDownEvent?

public static CountdownEvent _countDwn = new CountdownEvent(3);

static void Main(string[] args)
{
    new Thread(say).Start("hello 1");
    new Thread(say).Start("hello 2");
    new Thread(say).Start("hello 3");
    _countDwn.Wait();

    Console.WriteLine("done");
    Console.ReadLine();   
}    

public static void Go(object data, bool timedOut)
{
    Console.WriteLine("Started - " + data);
    // Perform task...
}

public static void say(Object o)
{
    Thread.Sleep(4000);
    Console.WriteLine(o);
    _countDwn.Signal(); 
}

UPD

我想得到类似于 sample with 的东西ManualResetEvent。无阻塞wait()

static ManualResetEvent _starter = new ManualResetEvent (false);

public static void Main()
{
  RegisteredWaitHandle reg = ThreadPool.RegisterWaitForSingleObject
                             (_starter, Go, "Some Data", -1, true);
  Thread.Sleep (5000);
  Console.WriteLine ("Signaling worker...");
  _starter.Set();
  Console.ReadLine();
  reg.Unregister (_starter);    // Clean up when we’re done.
}

public static void Go (object data, bool timedOut)
{
  Console.WriteLine ("Started - " + data);
  // Perform task...
}
4

1 回答 1

0

您可以使用与用于相同的方式ManualResetEvent

 RegisteredWaitHandle reg = ThreadPool.RegisterWaitForSingleObject
                         (_countDwn.WaitHandle, Go, "Some Data", -1, true);
 /// ...

 reg.Unregister(_countDwn.WaitHandle);
于 2017-12-05T12:48:12.203 回答