Do I need to Dispose a SemaphoreSlim

前端 未结 4 1211
梦毁少年i
梦毁少年i 2021-01-03 20:15

According to the documentation:

\"a SemaphoreSlim doesn\'t use a Windows kernel semaphore\".

Are there any special

4条回答
  •  死守一世寂寞
    2021-01-03 20:39

    For many other classes I would agree with i3arnon, but for SemaphoreSlim I'll go with Tim's comment. If you use SemaphoreSlim in a low-level class and have to dispose it then practically everything in your program will become IDisposable when in fact it is not necessary. This is all the more true given that AvailableWaitHandle is quite specialized and usually is not used.

    To protect against other coders accessing the AvailableWaitHandle, you can just wrap it in a non-disposable class. You see this for example in the wrappers by Cleary and by Hanselman, both based on a post by Stephen Toub (which by the way does not Dispose).

    P.S. As for the IDisposable contract, it should just be specified in the documentation that Dispose is only needed if AvailableWaitHandle is accessed.

提交回复
热议问题