O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required