System.Threading.Semaphore Class

Limits the number of threads that can access a resource or pool of resources concurrently.

See Also: Semaphore Members


public sealed class Semaphore : WaitHandle


Use the System.Threading.Semaphore class to control access to a pool of resources. Threads enter the semaphore by calling the erload:System.Threading.WaitHandle.WaitOne method, which is inherited from the System.Threading.WaitHandle class, and release the semaphore by calling the erload:System.Threading.Semaphore.Release method.

The count on a semaphore is decremented each time a thread enters the semaphore, and incremented when a thread releases the semaphore. When the count is zero, subsequent requests block until other threads release the semaphore. When all threads have released the semaphore, the count is at the maximum value specified when the semaphore was created.

There is no guaranteed order, such as FIFO or LIFO, in which blocked threads enter the semaphore.

A thread can enter the semaphore multiple times, by calling the erload:System.Threading.WaitHandle.WaitOne method repeatedly. To release some or all of these entries, the thread can call the parameterless Semaphore.Release method overload multiple times, or it can call the Semaphore.Release(int) method overload that specifies the number of entries to be released.

The System.Threading.Semaphore class does not enforce thread identity on calls to erload:System.Threading.WaitHandle.WaitOne or erload:System.Threading.Semaphore.Release. It is the programmer's responsibility to ensure that threads do not release the semaphore too many times. For example, suppose a semaphore has a maximum count of two, and that thread A and thread B both enter the semaphore. If a programming error in thread B causes it to call erload:System.Threading.Semaphore.Release twice, both calls succeed. The count on the semaphore is full, and when thread A eventually calls erload:System.Threading.Semaphore.Release, a System.Threading.SemaphoreFullException is thrown.

Semaphores are of two types: local semaphores and named system semaphores. If you create a System.Threading.Semaphore object using a constructor that accepts a name, it is associated with an operating-system semaphore of that name. Named system semaphores are visible throughout the operating system, and can be used to synchronize the activities of processes. You can create multiple System.Threading.Semaphore objects that represent the same named system semaphore, and you can use the erload:System.Threading.Semaphore.OpenExisting method to open an existing named system semaphore.

A local semaphore exists only within your process. It can be used by any thread in your process that has a reference to the local System.Threading.Semaphore object. Each System.Threading.Semaphore object is a separate local semaphore.


Namespace: System.Threading
Assembly: System (in System.dll)
Assembly Versions:,
Since: .NET 2.0