all groups > dotnet general > february 2008 >
You're in the

dotnet general

group:

how to read status of AutoResetEvent?


RE: how to read status of AutoResetEvent? AMercer
2/29/2008 1:15:00 PM
dotnet general:
[quoted text, click to view]

Re: how to read status of AutoResetEvent? AMercer
2/29/2008 3:56:00 PM
[quoted text, click to view]

So, it all depends on how often the OP wants to read it's current status.
Using WaitOne less frequently than, say, once a minute should pose no
problems. Using it more than a few times a second will be a problem. I
wonder what the OP had in mind?
how to read status of AutoResetEvent? buu
2/29/2008 7:51:49 PM
so, I have a private object as system.threading.AutoResetEvent, and I would
like to read it's current status.

currently I have an another boolean object wich I update together with an
AutoResetEvent, but I don't think it's the best practice....


Re: how to read status of AutoResetEvent? Jeroen Mostert
2/29/2008 8:18:46 PM
[quoted text, click to view]
You can't, for a good reason: it couldn't possibly be made thread-safe.

[quoted text, click to view]
Actually, it is, but only if you use locks to make this access thread-safe.

In many cases, using a monitor is more flexible and easier to get right than
using an AutoResetEvent. You can use Monitor.Pulse() and Monitor.Wait() to
let threads notify each other in much the same way.

bool conditionMet;
object conditionMonitor = new object();

lock (conditionMonitor ) {
if (!conditionMet) Monitor.Wait(conditionMonitor);
// conditionMet == true and no other thread is in this monitor
}

....

lock (conditionMonitor) {
conditionMet = true;
Monitor.Pulse(conditionMonitor);
}

--
Re: how to read status of AutoResetEvent? Jeroen Mostert
2/29/2008 11:54:35 PM
[quoted text, click to view]

This is a bad idea. First, it changes the state of the event if it's
signaled. You can set the event again, of course, but only if you take care
not to wait for it immediately again afterwards to "check" the status. In
the worst case you'd have to take over the responsibilities of the other
waiting threads.

Second, if the event is not signaled, waiting is likely to invoke a context
switch, which will probably take more than 1 millisecond, so this technique
doesn't scale. In fact, it's bizarrely more costly than checking a
self-maintained boolean, probably even if you factor in locking costs.

--
AddThis Social Bookmark Button