You cannot instantiate an instance of the Monitor class. The Monitor class, much like the
Interlocked class, is merely a containing namespace for a collection of shared methods that
do the work. Two such shared methods are Monitor.Enter() and Monitor.Exit(). These methods
prevent multiple threads from entering the code section outlined by Enter() and Exit().
nNote Monitors provide a way to ensure synchronization such that only one method, or a block of protected
code, executes at one time. A Mutex is typically used for the same task. However, the Monitor is
much lighter and faster. Monitor is appropriate when you must guard access to code within a single
process. Mutex is appropriate when you must guard access to a resource from multiple processes.
The CLR manages a sync block for every object instance in the process. Basically, it??™s a
flag of sorts, similar to the integer used in the examples of the previous section describing the
Interlocked class. When you obtain the lock on an object, this flag is set. When the lock is
released, this flag is reset. The Monitor class is the gateway to accessing this flag. The versatility
of this scheme is that every object instance in the CLR potentially contains one of these locks.
We say potentially because the CLR allocates them in a lazy fashion, since not every object
instance??™s lock will be utilized.
Pages:
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472