Thread Synchronization - Monitor
Monitor objects expose the ability to synchronize access to a region of code by taking and releasing a lock on a particular object using the Monitor.Enter, Monitor.TryEnter, and Monitor.Exit methods. Once you have a lock on a code region, you can use the Monitor.Wait, Monitor.Pulse, and Monitor.PulseAll methods. Wait releases the lock if it is held and waits to be notified. When Wait is notified, it returns and obtains the lock again. Both Pulse and PulseAll signal for the next thread in the wait queue to proceed.
C# lock statements use Monitor.Enter to take the lock and Monitor.Exit to release it. The advantage of using the language statements is that everything in the lock orSyncLock block is included in a Try statement. The Try statement has a Finally block to guarantee that the lock is released.Monitor locks objects (that is, reference types), not value types. While you can pass a value type to Enter and Exit, it is boxed separately for each call. Since each call creates a separate object, Enternever blocks, and the code it is supposedly protecting is not really synchronized. In addition, the object passed to Exit is different from the object passed to Enter, so Monitor throwsSynchronizationLockException with the message "Object synchronization method was called from an unsynchronized block of code."