ManualResetEvent的简单理解

看了很久的ManualResetEvent,但还是没看明白官方的解释,不妨让我们来看看定义的英文注释,或许更容易理解:
// Summary:
//     Initializes a new instance of the System.Threading.ManualResetEvent class
//     with a Boolean value indicating whether to set the initial state to signaled.
//
// Parameters:
//   initialState:
//     true to set the initial state signaled; false to set the initial state to
//     nonsignaled.
[SecuritySafeCritical]
public ManualResetEvent(bool initialState);

//
// Summary:
//     Sets the state of the event to nonsignaled, causing threads to block.
//
// Returns:
//     true if the operation succeeds; otherwise, false.
[SecuritySafeCritical]
public bool Reset();

//
// Summary:
//     Blocks the current thread until the current System.Threading.WaitHandle receives
//     a signal, using a 32-bit signed integer to measure the time interval.
//
// Parameters:
//   millisecondsTimeout:
//     The number of milliseconds to wait, or System.Threading.Timeout.Infinite
//     (-1) to wait indefinitely.
//
// Returns:
//     true if the current instance receives a signal; otherwise, false.
//
// Exceptions:
//   System.ObjectDisposedException:
//     The current instance has already been disposed.
//
//   System.ArgumentOutOfRangeException:
//     millisecondsTimeout is a negative number other than -1, which represents
//     an infinite time-out.
//
//   System.Threading.AbandonedMutexException:
//     The wait completed because a thread exited without releasing a mutex. This
//     exception is not thrown on Windows 98 or Windows Millennium Edition.
//
//   System.InvalidOperationException:
//     The current instance is a transparent proxy for a System.Threading.WaitHandle
//     in another application domain.
public virtual bool WaitOne(int millisecondsTimeout);

//
// Summary:
//     Sets the state of the event to signaled, allowing one or more waiting threads
//     to proceed.
//
// Returns:
//     true if the operation succeeds; otherwise, false.
[SecuritySafeCritical]
public bool Set();
总结:
  • ManualResetEvent 实例时接收一个Boolean类型的参数来初始化其状态,true表示畅通无阻的状态(signaled),线程不能阻塞,即使调用WaitOne也不能阻塞;false表示是可阻塞的状态(nonsignaled),可以调用WaitOne等方法来阻塞的。这里初始化的只是一个状态。
  • Reset方法把 ManualResetEvent 的状态设置为可阻塞的(nonsignaled),不管之前是什么状态,调用Reset都把状态设置为阻塞的(nonsignaled)。
  • WaitOne 阻塞当前线程直到别的线程调用Set方法,只有ManualResetEvent 的状态是可阻塞(nonsignaled)时,WaitOne才能真正的起到作用;
posted @ 2011-06-28 08:29  osEye  阅读(420)  评论(2编辑  收藏  举报