This topic has not yet been rated - Rate this topic

Semaphore Constructor (Int32, Int32)

April 12, 2014

Initializes a new instance of the Semaphore class, specifying the maximum number of concurrent entries and optionally reserving some entries.

Namespace:  System.Threading
Assembly:  System (in System.dll)
public Semaphore(
	int initialCount,
	int maximumCount
)

Parameters

initialCount
Type: System.Int32
The initial number of requests for the semaphore that can be granted concurrently.
maximumCount
Type: System.Int32
The maximum number of requests for the semaphore that can be granted concurrently.
ExceptionCondition
ArgumentException

initialCount is greater than maximumCount.

ArgumentOutOfRangeException

maximumCount is less than 1.

-or-

initialCount is less than 0.

This constructor initializes an unnamed semaphore. All threads that use an instance of such a semaphore must have references to the instance.

If initialCount is less than maximumCount, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times. If you do not want to reserve any entries for the thread that creates the semaphore, use the same number for maximumCount and initialCount.

The following code example creates a semaphore with a maximum count of three and an initial count of zero. The example starts five threads, which block waiting for the semaphore. The main thread uses the Release(Int32) method overload to increase the semaphore count to its maximum, allowing three threads to enter the semaphore. Each thread uses the Thread.Sleep method to wait for one second, to simulate work, and then calls the Release() method overload to release the semaphore. Each time the semaphore is released, the previous semaphore count is displayed. Console messages track semaphore use. The simulated work interval is increased slightly for each thread, to make the output easier to read.

Windows Phone OS

Supported in: 8.1, 8.0

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.