According to the documentation:
\"a
SemaphoreSlim
doesn\'t use a Windows kernel semaphore\".
Are there any special
Yes.
It may use a ManualResetEvent
that uses a SafeWaitHandle
which is a SafeHandle
and it has an unmanaged handle.
You can see it in the reference source here.
SafeHandle
is finalizable so if you don't dispose of it (by disposing of the SemaphoreSlim
) it will go to the finalizer that will need to do that for you. Since the finalizer is a single thread it may get overworked in certain situations so it's always advisable to dispose finalizable objects.
You should always call Dispose()
on any class implementing IDisposable
(or put it inside a using
statement) and not base your decision on its internal implementation. The class author already made that decision for you by implementing the IDisposable
interface.
If you access the AvailableWaitHandle property, then Yes, you must call Dispose() to cleanup unmanaged resources.
If you do not access AvailableWaitHandle, then No, calling Dispose() won't do anything important.
SemaphoreSlim will create a ManualResetEvent on demand if you access the AvailableWaitHandle. This may be useful, for example if you need to wait on multiple handles. If you do access the AvailableWaitHandle property, and then fail to call Dispose() you will have a leaked ManualResetEvent, which presumably wraps a handle to an unmanaged CreateEvent resource that needs a corresponding call to CloseHandle to clean up.
As other posters have pointed out, you should call Dispose() when you are done with any object that implements IDisposable. In this case, there are several risks to ignoring that practice, even though it may technically be safe to do so:
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.