-1

As the title says, is this a valid implementation? I'm aware of the lock statement's problems, but due to requirements it must be used. Is this code valid?

lock (richTextBox)
{
    Monitor.Wait(richTextBox);
    richTextBox.AppendText("Text");
    Monitor.PulseAll(richTextBox);
}
3
  • 1
    Can you explain in more detail what "is this a valid implementation" means? What problems do you suspect that are causing you to bring the code here? For example, "does it compile" is one measure of valid code. I'm sure it does compile. But you could have used a compiler to figure that out. As for if it correctly implements the algorithm, have you tried it out? Did it work? What problems did you encounter? Dec 18, 2011 at 23:20
  • 1
    I think people are being a little harsh with this question, there is a clear misunderstanding of how monitors work here, and it warrants correction. Please comment when you down-vote. Dec 18, 2011 at 23:49
  • Thanks @MerlynMorgan-Graham for the cogent description of the weaknesses of this question. Dec 18, 2011 at 23:53

1 Answer 1

2

This code doesn't make sense because every thread will block on the Monitor.Wait, and none will ever be release unless some other block of code calls Monitor.PulseAll. Normally waits/pulses are used in producer/consumer type scenarios (i.e. one or more threads are waiting for another thread to accomplish some task or provide some data).

If you're question is more regarding the use of lock statement rather than: Monitor.Enter/Monitor.Exit, that part is fine.

According to the MSDN article:

lock(obj) { ... } 

should be the same as:

Monitor.Enter(obj); try { ... } finally { Monitor.Exit(obj); }
4
  • Thanks for your input - I just wanted clarification to see if I understood the concept of Monitor.Wait/Pulse. I see what you mean regarding the Wait method.
    – Dot NET
    Dec 18, 2011 at 23:20
  • It's important to understand that when Monitor.Wait is called the lock is released, thus allowing other threads to enter the lock. When PulseAll is called all the threads that previously called wait will be released, but not simultaneously, since only one can re-obtain the lock at a time. When another thread calls Pulse/PulseAll the threads blocked on a Wait are moved to ready queue, but don't re-acquire the lock and proceed until the thread that did the pulsing releases the lock (either by exiting the block, or by calling Wait itself. Dec 18, 2011 at 23:42
  • Between the wikipedia article on the concept of Monitors en.wikipedia.org/wiki/Monitor_%28synchronization%29 and the MSDN article on the Monitor class: msdn.microsoft.com/en-us/library/system.threading.monitor.aspx you should be able to gain a fairly solid understanding of their function. Dec 19, 2011 at 0:11
  • Thanks for your assistance, I'm understanding better now.
    – Dot NET
    Dec 19, 2011 at 17:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.