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.

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.

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.

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.

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 ...

Get C# in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.