Use of IDisposable interface

1. If a class implements IDisposable, its Dispose method releases resources that are expensive or scarce.

Cost of calling Dispose : try – catch – finally execution.

Advantage of calling Dispose : Release expensive resources immediately, so that the other objects need not wait for GC to finalize the object and release the resource.

This advantage would in general outweigh the cost. The only scenario where this wont hold true would be when the resource is not, if that’s the case the implementation of IDisposable itself is pointless. One could use profiling to determine if the resource is expensive and implement IDisposable only if required.

2. In case IDisposable is used for thread synchronization calling Dispose is a must since the other threads are waiting for the synchronization object.

I think the right way would be to call dispose as this is a standard pattern that developers must use.

3. As far as SQL connection object is concerned

a. Close method – returns the Connection to the pool. Use this if you plan to reuse the Connection object because it still holds the connection string.

b. Dispose method – releases managed resources, releases unmanaged resources if any, and calls Close (which would return the connection to the pool). Use this if you don’t plan to reuse the connection object.

Note : Both Close and Dispose return the connection to the pool.

In general, if a class provides both Close and Dispose, choosing between them would depend on the class and the requirement and there is no one answer that applies to all.

Comments (2)

  1. alan.dean says:

    "1. If a class implements IDisposable, its Dispose method releases resources that are expensive or scarce."

    … or unmanaged.

  2. mehndi says:

    I agree with you alan. Thanks for pointing it out.

    Calling the Dispose method on an object does two things.

    Firstly, it cleans up any unmanaged resources that were in use by your object.

    Secondly, it marks the object so that the GC would not call its Finalize method when it collects it – the resources have been cleaned up already in your Dispose method. This way, you save the overhead of the GC’s call to Finalize, and you can clean up your object at the most appropriate time.

Skip to main content