Advertisement
ivandrofly

SemaphoreSlim vs Semaphore

Aug 21st, 2023
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. 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.
  2. There are some key differences between these two:
  3.  
  4. Semaphore:
  5. Semaphore is heavier and works in both local and remote(named semaphore) scenarios. This makes it suitable for cross-process synchronization.
  6. 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.
  7. It is released automatically when the process or thread that acquired the semaphore ends unexpectedly.
  8.  
  9. SemaphoreSlim:
  10. SemaphoreSlim is a lightweight alternative, which provides better performance for synchronization within a single process(i.e. in a single AppDomain).
  11. The wait and release methods do not involve a transition to kernel mode, it’s more efficient.
  12. It also has async support (WaitAsync()), which Semaphore does not have.
  13. 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.
  14. Let me know if you need help with anything else.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement