新的AutoResetEvent(真)在C#用法?AutoResetEvent

2023-09-04 23:43:27 作者:星河入怀

我想知道,

为什么的我会永远想传递一个的AutoResetEvent 的构造函数?

Why would I ever want to pass a true in the ctor of AutoResetEvent ?

我创建了一个的WaitHandle 使任何人谁就会调用 WaitOne的()实际上将等

I create a waitHandle so that anyone who will call WaitOne() will actually wait.

如果我有实例,它,这将是,如果它被立刻发出信号 - 这是像一个正常的流程,而无需等待

If I instance it with a true , it will be as if it was immediatly signaled - which is like a normal flow without waiting.

  EventWaitHandle _waitHandle = new AutoResetEvent (false);

void Main()
{
  new Thread (Waiter).Start();
    Thread.Sleep (1000);                   
    _waitHandle.Set();                    

Console.ReadLine();
}
  void Waiter()
  {
    Console.WriteLine ("AAA");
    _waitHandle.WaitOne();                 
    Console.WriteLine ("BBBB");
  }

输出:

AAA...(delay)...BBB

更改为:的EventWaitHandle _waitHandle =新的AutoResetEvent(真); 和输出将是:

AAABBB

问题

为什么我会永远想做到这一点? (通过)?

推荐答案

该方案将是在第一的线程调用的WaitOne 应立即穿过,而不会阻塞。

The scenario would be that the first thread that calls WaitOne should immediately pass through, without blocking.

检查 Silverlight的文档的AutoResetEvent (奇怪的是该文档是不一样的.NET版本):

Check the Silverlight documentation for AutoResetEvent (strangely enough the doc is not the same on the .Net versions):

指定的初始化状态创建一个的AutoResetEvent 的   信号状态。如果你想第一个线程,这是非常有用的   等待的AutoResetEvent 被立即释放,不   阻止。

Specifying true for initialState creates an AutoResetEvent in the signaled state. This is useful if you want the first thread that waits for the AutoResetEvent to be released immediately, without blocking."