16.2 Common Thread Types

Much of the functionality of threads is provided through the classes in the System.Threading namespace. The most basic thread class to understand is the Monitor class, which is explained next.

16.2.1 The Monitor Class

The System.Threading.Monitor class provides an implementation of Hoare's Monitor that allows you to use any reference-type instance as a monitor.

16.2.2 The Enter and Exit Methods

The Enter( ) and Exit( ) methods respectively obtain and release a lock on an object. If the object is already held by another thread, Enter( ) waits until the lock is released, or the thread is interrupted by a ThreadInterruptedException. Every call to Enter( ) for a given object on a thread should be matched with a call to Exit( ) for the same object on the same thread.

16.2.3 The TryEnter Methods

The TryEnter( ) methods are similar to the Enter( ) method, but they don't require a lock on the object to proceed. These methods return true if the lock is obtained, and false if it isn't, optionally passing in a timeout parameter that specifies the maximum time to wait for the other threads to relinquish the lock.

16.2.4 The Wait Methods

The thread holding a lock on an object may call one of the Wait( ) methods to temporarily release the lock and block itself, while it waits for another thread to notify it by executing a pulse on the monitor. This approach can tell a worker thread there is work to perform on that object. The overloaded versions of Wait( ) allow you to specify a timeout that reactivates the thread if a pulse hasn't arrived within the specified duration. When the thread wakes up, it reacquires the monitor for the object (potentially blocking until the monitor becomes available). Wait( ) returns true if the thread is reactivated by another thread pulsing the monitor and returns false if the Wait( ) call times out without receiving a pulse.

16.2.5 The Pulse and PulseAll Methods

A thread holding a lock on an object may call Pulse( ) on that object to wake up a blocked thread as soon as the thread calling Pulse( ) has released its lock on the monitor. If multiple threads are waiting on the same monitor, Pulse( ) activates only the first in the queue (successive calls to Pulse( ) wake up other waiting threads, one per call). The PulseAll( ) method successively wakes up all the threads.

    Part II: Programming with the .NET Framework
    Part IV: API Quick Reference