How do I choose between Semaphore and SemaphoreSlim?

后端 未结 5 673
余生分开走
余生分开走 2020-12-04 18:41

Their public interfaces appear similar. The documentation states that the SemaphoreSlim is a lightweight alternative and doesn\'t use Windows Kernel semaphores. This resou

5条回答
  •  清歌不尽
    2020-12-04 19:26

    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.

提交回复
热议问题