SemaphoreSlim Class
TOC
Collapse the table of content
Expand the table of content

SemaphoreSlim Class

.NET Framework (current version)
 

Represents a lightweight alternative to Semaphore that limits the number of threads that can access a resource or pool of resources concurrently.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

System.Object
  System.Threading.SemaphoreSlim

<ComVisibleAttribute(False)>
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,
	ExternalThreading := True)>
Public Class SemaphoreSlim
	Implements IDisposable

NameDescription
System_CAPS_pubmethodSemaphoreSlim(Int32)

Initializes a new instance of the SemaphoreSlim class, specifying the initial number of requests that can be granted concurrently.

System_CAPS_pubmethodSemaphoreSlim(Int32, Int32)

Initializes a new instance of the SemaphoreSlim class, specifying the initial and maximum number of requests that can be granted concurrently.

NameDescription
System_CAPS_pubpropertyAvailableWaitHandle

Returns a WaitHandle that can be used to wait on the semaphore.

System_CAPS_pubpropertyCurrentCount

Gets the number of remaining threads that can enter the SemaphoreSlim object.

NameDescription
System_CAPS_pubmethodDispose()

Releases all resources used by the current instance of the SemaphoreSlim class.

System_CAPS_protmethodDispose(Boolean)

Releases the unmanaged resources used by the SemaphoreSlim, and optionally releases the managed resources.

System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethodFinalize()

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_protmethodMemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_pubmethodRelease()

Releases the SemaphoreSlim object once.

System_CAPS_pubmethodRelease(Int32)

Releases the SemaphoreSlim object a specified number of times.

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

System_CAPS_pubmethodWait()

Blocks the current thread until it can enter the SemaphoreSlim.

System_CAPS_pubmethodWait(CancellationToken)

Blocks the current thread until it can enter the SemaphoreSlim, while observing a CancellationToken.

System_CAPS_pubmethodWait(Int32)

Blocks the current thread until it can enter the SemaphoreSlim, using a 32-bit signed integer that specifies the timeout.

System_CAPS_pubmethodWait(Int32, CancellationToken)

Blocks the current thread until it can enter the SemaphoreSlim, using a 32-bit signed integer that specifies the timeout, while observing a CancellationToken.

System_CAPS_pubmethodWait(TimeSpan)

Blocks the current thread until it can enter the SemaphoreSlim, using a TimeSpan to specify the timeout.

System_CAPS_pubmethodWait(TimeSpan, CancellationToken)

Blocks the current thread until it can enter the SemaphoreSlim, using a TimeSpan that specifies the timeout, while observing a CancellationToken.

System_CAPS_pubmethodWaitAsync()

Asynchronously waits to enter the SemaphoreSlim.

System_CAPS_pubmethodWaitAsync(CancellationToken)

Asynchronously waits to enter the SemaphoreSlim, while observing a CancellationToken.

System_CAPS_pubmethodWaitAsync(Int32)

Asynchronously waits to enter the SemaphoreSlim, using a 32-bit signed integer to measure the time interval.

System_CAPS_pubmethodWaitAsync(Int32, CancellationToken)

Asynchronously waits to enter the SemaphoreSlim, using a 32-bit signed integer to measure the time interval, while observing a CancellationToken.

System_CAPS_pubmethodWaitAsync(TimeSpan)

Asynchronously waits to enter the SemaphoreSlim, using a TimeSpan to measure the time interval.

System_CAPS_pubmethodWaitAsync(TimeSpan, CancellationToken)

Asynchronously waits to enter the SemaphoreSlim, using a TimeSpan to measure the time interval, while observing a CancellationToken.

Semaphores are of two types: local semaphores and named system semaphores. The former is local to an app. The latter is visible throughout the operating system and is suitable for inter-process synchronization. The SemaphoreSlim is a lightweight alternative to the Semaphore class that doesn't use Windows kernel semaphores. Unlike the Semaphore class, the SemaphoreSlim class doesn’t support named system semaphores. You can use it as a local semaphore only. The SemaphoreSlim class is the recommended semaphore for synchronization within a single app.

A lightweight semaphore controls access to a pool of resources that is local to your application. When you instantiate a semaphore, you can specify the maximum number of threads that can enter the semaphore concurrently. You also specify the initial number of threads that can enter the semaphore concurrently. This defines the semaphore's count.

The count is decremented each time a thread enters the semaphore, and incremented each time a thread releases the semaphore. To enter the semaphore, a thread calls one of the Wait or WaitAsync overloads. To release the semaphore, it calls one of the Release overloads. When the count reaches zero, subsequent calls to one of the Wait methods block until other threads release the semaphore. If multiple threads are blocked, there is no guaranteed order, such as FIFO or LIFO, that controls when threads enter the semaphore.

The basic structure for code that uses a semaphore to protect resources is:


' Enter semaphore by calling one of the Wait or WaitAsync methods.
SemaphoreSlim.Wait()
' 
' Execute code protected by the semaphore. 
'
SemaphoreSlim.Release()

When all threads have released the semaphore, the count is at the maximum value specified when the semaphore was created. The semaphore's count is available from the CurrentCount property.

System_CAPS_importantImportant

The SemaphoreSlim class doesn’t enforce thread or task identity on calls to the Wait, WaitAsync, and Release methods. In addition, if the SemaphoreSlim(Int32) constructor is used to instantiate the SemaphoreSlim object, the CurrentCount property can increase beyond the value set by the constructor. It is the programmer's responsibility to ensure that calls to Wait or WaitAsync methods are appropriately paired with calls to Release methods.

The following example creates a semaphore with a maximum count of three threads and an initial count of zero threads. The example starts five tasks, all of which block waiting for the semaphore. The main thread calls the Release(Int32) overload to increase the semaphore count to its maximum, which allows three tasks to enter 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.

Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Private semaphore As SemaphoreSlim
    ' A padding interval to make the output more orderly.
    Private padding As Integer

   Public Sub Main()
      ' Create the semaphore.
      semaphore = New SemaphoreSlim(0, 3)
      Console.WriteLine("{0} tasks can enter the semaphore.",
                        semaphore.CurrentCount)
      Dim tasks(4) As Task

      ' Create and start five numbered tasks.
      For i As Integer = 0 To 4
         tasks(i) = Task.Run(
            Sub()
               ' Each task begins by requesting the semaphore.
               Console.WriteLine("Task {0} begins and waits for the semaphore.",
                              Task.CurrentId)
               semaphore.Wait()

               Interlocked.Add(padding, 100)

               Console.WriteLine("Task {0} enters the semaphore.", Task.CurrentId)

               ' The task just sleeps for 1+ seconds.
               Thread.Sleep(1000 + padding)

               Console.WriteLine("Task {0} releases the semaphore previous count: {1}.",
                                 Task.CurrentId, semaphore.Release())
            End Sub )
      Next

      ' Wait for half a second, to allow all the tasks to start and block.
      Thread.Sleep(500)

      ' Restore the semaphore count to its maximum value.
      Console.Write("Main thread calls Release(3) --> ")
      semaphore.Release(3)
      Console.WriteLine("{0} tasks can enter the semaphore.",
                        semaphore.CurrentCount)
      ' Main thread waits for the tasks to complete.
      Task.WaitAll(tasks)

      Console.WriteLine("Main thread exits.")
   End Sub
End Module
' The example displays output like the following:
'       0 tasks can enter the semaphore.
'       Task 1 begins and waits for the semaphore.
'       Task 5 begins and waits for the semaphore.
'       Task 2 begins and waits for the semaphore.
'       Task 4 begins and waits for the semaphore.
'       Task 3 begins and waits for the semaphore.
'       Main thread calls Release(3) --> 3 tasks can enter the semaphore.
'       Task 4 enters the semaphore.
'       Task 1 enters the semaphore.
'       Task 3 enters the semaphore.
'       Task 4 releases the semaphore; previous count: 0.
'       Task 2 enters the semaphore.
'       Task 1 releases the semaphore; previous count: 0.
'       Task 3 releases the semaphore; previous count: 0.
'       Task 5 enters the semaphore.
'       Task 2 releases the semaphore; previous count: 1.
'       Task 5 releases the semaphore; previous count: 2.
'       Main thread exits.

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1

All public and protected members of SemaphoreSlim are thread-safe and may be used concurrently from multiple threads, with the exception of Dispose, which must be used only when all other operations on the SemaphoreSlim have completed.

Return to top
Show:
© 2016 Microsoft