If a class has a Dispose method the best practice is to call it. the reason
behind that is that Dispose runs when called, whereas setting the object to
null simply adds a entry to the Finalize queue in GC, and we cannot
determine when GC will run.
There is no performance benefit in implementing the Dispose method on types that use only managed resources (such as arrays) because they are automatically reclaimed by the garbage collector. Use the Dispose method primarily on managed objects that use native resources and on COM objects that are exposed to the .NET Framework. Managed objects that use native resources (such as the FileStream class) implement the IDisposable interface.
An elegant means of inoking Dispose that have adopted is using the "using" construct. For those of you who may not be familiar with the construct, it provide a means to implicity invoke Dispose() on an instance that implements IDisposable even if an exception is thrown durring the operation. The following is an example of the using construct:
using(DisposableClass dc = new DisposableClass())
{
dc.PerformActionOnUmanagedResources();
dc.PerformAnotherActionOnUmanagedResources();
}
In the previous example, if an exception was thrown in the PerformActionOnUmanagedResources() method, although the PerformAnotherActionOnUmanagedResources() method would not be processed, the using block will still implicity invoke the Dispose method on dc ensuring the realese of any unmanaged resources.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…