Monitor Pulse/PulseAll/Wait question

R

Rene

Hi,

Could anyone explain to me why calls to:

Monitor.Pulse(obj);
Monitor.PulseAll(obj);
Monitor.Wait(obj);

Need to happen between the Monitor.Enter() and Monitor.Exit() calls?

I realize that some of this call may not make "conceptual" sense if they are
called outside the Monitor.Enter() and Monitor.Exit() methods but my guess
is that you could design something using the calls outside the
Monitor.Enter() and Monitor.Exit() methods and get something to work
although there would be probably betters ways to accomplish this.

So my question again is, why does the framework throws and error if the call
and not made between the Monitor.Enter() and Monitor.Exit() methods?

Thanks.
 
J

Jon Skeet [C# MVP]

Rene said:
Could anyone explain to me why calls to:

Monitor.Pulse(obj);
Monitor.PulseAll(obj);
Monitor.Wait(obj);

Need to happen between the Monitor.Enter() and Monitor.Exit() calls?

To avoid race conditions, basically. You need to be able to atomically
wait and release the lock, then wake up and acquire the lock.

I suspect it *could* have been designed so that you didn't need to have
the lock in order to pulse it, but usually you'd want to be in the lock
anyway, because you typically make a change to a shared resource before
pulsing, and you also typically want that shared resource when you're
woken up.
 
J

Jon Skeet [C# MVP]

Rene said:
Thanks Jon!

That makes sense, I appreciate your help.

Phew - I'm glad it makes sense without further explanation. I have to
be in a really coherent state of mind in order to explain *why* there's
a possible race condition without owning the lock first, and I'm
certainly not there at the moment.
 
R

Rene

He he he.

Actually, I got get right away but to be honest with you I was kind of upset
about it because I wanted to so see if I could figure it out myself so I
have been thinking about this for two days now and the answer you gave me
never crossed my mind!!

This is probably because I have been reading about multithreading for a
couple of days now and I just about had enough and probably need to take
break from the subject.

Thanks again!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top