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.
Just as any thread is allowed put an item into a blocking queue, and any thread is allowed to take an item out, so any thread can increment or decrement the count of a semaphore.
You can check to see if a Semaphore is signaled by calling WaitOne and passing a timeout value of 0 as a parameter. This will cause WaitOne to return immediately with a true or false value indicating whether the semaphore was signaled.
The semaphore class lets you set a limit on the number of threads that have access to a critical section. The class is used to control access to a pool of resources. System. Threading. Semaphore is the namespace for Semaphore because it has all the methods and properties required to implement Semaphore.
One difference is that SemaphoreSlim
does not permit named semaphores, which can be system-wide. This would mean that a SemaphoreSlim could not be used for cross-process synchronization.
The MSDN documentation also indicates that SemSlim should be used when "wait times are expected to be very short". That would usually dovetail nicely with the idea that the slim version is more lightweight for most of the trade offs.
SemaphoreSlim is based on SpinWait and Monitor, so the thread that waits to acquire the lock is burning CPU cycles for some time in hope to acquire the lock prior to yielding to another thread. If that does not happen, then the threads lets the systems to switch context and tries again (by burning some CPU cycles) once the OS schedules that thread again. With long waits this pattern can burn through a substantial amount of CPU cycles. So the best case scenario for such implementation is when most of the time there is no wait time and you can almost instantly acquire the lock.
Semaphore relies on the implementation in OS kernel, so every time when you acquire the lock, you spend quite a lot of CPU cycles, but after that the thread simply sleeps for as long as necessary to get the lock.
The MSDN documentation describes the difference.
In one sentence:
Regarding "short times" controversy:
At least SemaphoreSlim MSDN documentation states that
The SemaphoreSlim class is the recommended semaphore for synchronization within a single app.
in Remarks section. Same section also tells the main difference between Semaphore and SemaphoreSlim:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With