views:

45

answers:

2

I want to implement the following logic:

  private static AutoResetEvent _autoResetEvent = new AutoResetEvent(false);

  static void Main(string[] args)
  {
     var someObjectInstance = new SomeObject();
     someObjectInstance.SomeEvent += SomeEventHandler;
     _autoResetEvent.WaitOne();
     //...
  }

  static void SomeEventHandler()
  {
     _autoResetEvent.Set();
  }

So the Main method should wait till SomeEvent is called the first time. As I understand _autoResetEvent.WaitOne blocks the thread so SomeEvent should be raised in another thread. But how can I guarantee it?

A: 

Once the main thread will reach _autoResetEvent.WaitOne(), it will be blocked until that Event object will be signaled. If the AutoResetEvent object never gets signaled, then the thread that waits on WaitOne() will block indefinitely (assuming no one throws an InterruptException on the main thread, and no timeout value was passed to the WaitOne() method).

Liran
A: 

So you want the event to be raised from another thread? The following code would do just that.

public class Program
{
  private static AutoResetEvent _autoResetEvent = new AutoResetEvent(false); 

  static void Main(string[] args) 
  { 
    var someObjectInstance = new SomeObject(); 
    someObjectInstance.SomeEvent += SomeEventHandler;
    var thread = new Thread(
      () =>
      {
        someObjectInstance.DoSomethingThatRaisesSomeEvent();
      });
    thread.Start();
    _autoResetEvent.WaitOne(); 
    //... 
  } 

  static void SomeEventHandler() 
  { 
    _autoResetEvent.Set(); 
  }
}
Brian Gideon