I'm creating some "instrumentation" inside a multi-threaded server in .NET (C#).
It's fairly easy to check the value of a .NET ManualResetEvent
without concern for changing the value:
aManualResetEvent.WaitOne( 0 );
returns a boolean without waiting on the event.
However, I seem to be at a loss for getting the same information from an AutoResetEvent
; if you call anAutoResetEvent.WaitOne( 0 )
on a set
event, it will reset the event while returning (by definition).
The best option I can determine at this point is to change the AutoResetEvent
to a ManualResetEvent
and manually reset when actually testing the event:
ManualResetEvent theEventFormerlyKnownAsAutoResetEvent;
...
// Using the event:
if ( theEventFormerlyKnownAsAutoResetEvent.WaitOne( timeout )
{
theEventFormerlyKnownAsAutoResetEvent.Reset();
...
}
...
// Instrumentation to get event state (shouldn't change anything):
bool eventIsSet = theEventFormerlyKnownAsAutoResetEvent.WaitOne( 0 );
// Update instrumentation
Is there a better way of checking the state of an AutoResetEvent
? I would prefer the intrinsic atomicity of the AutoResetEvent
if possible.
The point of AutoResetEvent
is to release one and only one waiting thread when the event transitions to a signalled state. If you used the signalled state to do something specific in one thread, you risk getting into a race condition or a deadlock between threads if another thread can still wait on the event's signal--one of the reasons for using AutoResetEvent
.
If you provide more detail about what you're trying to accomplish, maybe someone can provide an alternative that would help.