Tom Deseyn Tom Deseyn - 8 months ago 139
C# Question

Do I need to Dispose a SemaphoreSlim

According to the documentation:

doesn't use a Windows kernel semaphore".

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



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.