Search code examples
c#.netsemaphoredisposeidisposable

Do I need to Dispose a SemaphoreSlim?


According to the documentation:

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

Are there any special resources used by the SemaphoreSlim which make it important to call Dispose when the SemaphoreSlim will no longer be used?


Solution

  • 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.