Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Both Semaphore and SemaphoreSlim are synchronization primitives provided by .NET Framework. They can be used to limit the number of threads that can access some resources.
- There are some key differences between these two:
- Semaphore:
- Semaphore is heavier and works in both local and remote(named semaphore) scenarios. This makes it suitable for cross-process synchronization.
- It uses kernel-mode constructs, it involves a transition to kernel mode to wait or release the semaphore, quite expensive in terms of CPU time.
- It is released automatically when the process or thread that acquired the semaphore ends unexpectedly.
- SemaphoreSlim:
- SemaphoreSlim is a lightweight alternative, which provides better performance for synchronization within a single process(i.e. in a single AppDomain).
- The wait and release methods do not involve a transition to kernel mode, it’s more efficient.
- It also has async support (WaitAsync()), which Semaphore does not have.
- In general, if you need to synchronize threads across processes, then you should use Semaphore, otherwise use SemaphoreSlim for improve performance within a single process. Additionally, when async programming model is required you should use SemaphoreSlim.
- Let me know if you need help with anything else.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement