Search code examples
.netmultithreadingdisposesemaphore

Is it necessary to call Dispose on a Semaphore?


class myclass 
{
    private Semaphore _sync;

    myclass ()
    {
          _sync = new Semaphore(1,1);
    }

    doasync()
    {
           _sync.WaitOne();
           //do some stuff
           _sync.Release();
    }
}


 somefunctionsomewhere() 
 {
     var myobject = new myclass();    
     //spawn 100 threads that all call myobject.doasync()
 }

is the above safe + clean? Will the both _sync get disposed and myclass be collected when all 100 threads have finished doing their async work?

If not, what's the best way to know when to call _sync.Dispose() ?


Solution

  • Short answer: No, you don't need to call Dispose().

    Long answer:

    Though it is recommended to call Dispose() when you are finished using the Semaphore, the garbage collector will take care of the semaphore's resources sooner or later.

    An explicit call to Dispose() will guarantee an early release of the associated resource, but it's only required if you are creating and forgetting a lot of Semaphore instance in a short amount of time.

    And if you call Dispose(), it is perfectly fine to use a simple Dispose() call. You don't need to create a finalizer ~myclass() because that would just duplicate what's already done the Semaphore implementation.