How do I choose between Semaphore and SemaphoreSlim?

后端 未结 5 672
余生分开走
余生分开走 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:07

    I looked at the source code here and this is what I came up with:

    1. Both Semaphore and SemaphoreSlim derive from WaitHandle which internally uses Win32 native handle. Which is why you need to Dispose() both. So the notion that Slim is lightweight is suspect.

    2. SemaphoreSlim uses SpinWait internally while Semaphore does not. That tells me that in cases where the wait is expected to be long, Semaphore should do better at least in the sense that it will not choke out your CPU.

提交回复
热议问题