c# - AutoResetEvent Reset immediately after Set -


consider following pattern:

private autoresetevent signal = new autoresetevent(false);  private void work() {     while (true)     {         thread.sleep(5000);         signal.set();         //has waiting thread been signaled now?         signal.reset();     } }  public void waitfornextevent() {     signal.waitone(); } 

the purpose of pattern allow external consumers wait event (e.g. - message arriving). waitfornextevent not called within class.

to give example should familiar, consider system.diagnostics.process. exposes exited event, exposes waitforexit method, allows caller wait synchronously until process exits. trying achieve here.

the reason need signal.reset() if thread calls waitfornextevent after signal.set() has been called (or in other words, if .set called when no threads waiting), returns immediately, event has been signaled.

the question

  • is guaranteed thread calling waitfornextevent() signaled before signal.reset() called? if not, other solutions implementing waitfor method?

instead of using autoresetevent or manualresetevent, use this:

public sealed class signaller {     public void pulseall()     {         lock (_lock)         {             monitor.pulseall(_lock);         }     }      public void pulse()     {         lock (_lock)         {             monitor.pulse(_lock);         }     }      public void wait()     {         wait(timeout.infinite);     }      public bool wait(int timeoutmilliseconds)     {         lock (_lock)         {             return monitor.wait(_lock, timeoutmilliseconds);         }     }      private readonly object _lock = new object(); } 

then change code so:

private signaller signal = new signaller();  private void work() {     while (true)     {         thread.sleep(5000);         signal.pulse(); // or signal.pulseall() signal waiting threads.     } }  public void waitfornextevent() {     signal.wait(); } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -