Can ManualResetEvent be used to supersede a boolean

401 views Asked by At

This is admittedly an unusual question; I would never recommend replacing a boolean with a ManualResetEvent in typical .NET development. In this case, I already need a ManualResetEvent to indicate connection status to another thread; given that, it occurs to me that the use of a boolean with the same semantic meaning is redundant.

OK, specifics: I have a worker thread that should process messages when the following conditions are true:

  • "Client" connected
  • "Recipient" connected

The "client" and "recipient" connections are TCP sockets which other threads are monitoring; when either connection status changes, the corresponding WaitHandle will be set (Connected) or reset (Disconnected).

Originally, I had a boolean indicated the connection state (for UI). Now that I am using WaitHandles to signal the worker thread, it seems advantageous to eliminate the boolean state variables entirely and just use the WaitHandles.

waitEvent.WaitOne( 0 )

returns the state of the handle without blocking, making it functionally identical to testing a boolean value (with the added advantage of thread-safe operation).

So, given that I am already going to be using the WaitHandles, and I don't like the idea of maintaining the state (same semantic meaning) into two different variables, is there any reason why I can't just use the WaitHandles? The most significant counter-argument I can think of is runtime performance: time to test a boolean vs. time to test the WaitHandle; but I don't think performance will be that significantly affected.

Am I missing anything significant here?

Thanks!

2

There are 2 answers

4
FMM On BEST ANSWER

The benefit of just using the ManualResetEvent are that you only have one variable tracking the same state. However, as you mentioned, there will be overhead to read the state back out.

You have to ask if that overhead is significant enough to justify tracking the same state in two places and risk them becoming out-of-sync.

0
Brad Semrad On

There are multiple ways of doing things. This is one of those cases. There should be no difference assuming you use the boolean correctly. The one consideration would be memory (object takes more then a boolean) but most likely minuscule. Either one I would recommend but since you are using Threading to signal events I would suggest the WaitHandles as these are what they are designed to do.