Rule Definition
If a type inherits from a disposable type, it must call the Dispose method of the base type from within its own Dispose method in order to make sure all allocated resources are released properly and timely.
Failing to do so can provoke a resource leak that will lead to serious application availability and stability issues.
Remediation
keep dispose(bool) method in try-finally block and inside finally block make use of base.Dispose() or MyBase.Finalize() method.
Violation Code Sample
protected virtual void Dispose(bool disposing) { if (disposing) { // Dispose managed resources } // Free native resources }
Fixed Code Sample
protected override void Dispose(bool disposing)
{
if(!this.disposed)
{
try
{
if(disposing)
{
// Release the managed resources you added in
// this derived class here.
addedManaged.Dispose();
}
// Release the native unmanaged resources you added
// in this derived class here.
CloseHandle(addedNative);
this.disposed = true;
}
finally
{
// Call Dispose on your base class.
base.Dispose(disposing);
}
}
}
Reference
Resource Management in .NET
by Krzysztof Cwalina
Program Manager - Microsoft .NET Framework
http://www.gotdotnet.com/team/libraries/whitepapers/resourcemanagement/resourcemanagement.aspx
Implementing IDisposable and the Dispose Pattern Properly
By Scott Dorman
http://www.codeproject.com/useritems/idisposable.asp
Chris Lyon's WebLog
http://blogs.msdn.com/clyon/archive/2004/09/23/233464.aspx
Understanding Garbage Collection in the .NET Framework
By Dipal Choksi
http://www.c-sharpcorner.com/UploadFile/DipalChoksi/UnderstandingGarbageCollectioninNETFramework11292005051110AM/UnderstandingGarbageCollectioninNETFramework.aspx
Related Technologies
Technical Criterion
Efficiency - Memory, Network and Disk Space Management
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.