... continued
Continues the discussion on the Monitor class.
We'll cover the following...
Ping Pong Example
We can rewrite our ping-pong example without busy waiting using Monitor. The two threads Wait() and Pulse() to not busy wait. The code is self-explanatory and appears below, the widget runs for ten seconds and then timees out.
Using Value Types
One of the most common mistakes when using the Monitor class is to pass value types as the object to synchronize on. Consider the snippet below:
If we run the example above we get an object not synchronized exception. When we pass a value type to Monitor's static methods, it is automatically boxed to a reference type. The conversion is implicit and each of three methods in the above example receive different objects as arguments that box the value type! This is the reason the code widget below throws up an exception.
Contrast the above with the ...