DBConnection conn = new DBConnection();
try
{
conn.Open();
//...
}
finally
{
conn.Close();
}
* This source code was highlighted with Source Code Highlighter .
And complicated:public class MyResource: IDisposable
{
private bool disposed = false ;
// IDisposable
//
//
public void Dispose()
{
Dispose( true ); //
GC.SuppressFinalize( this ); // , GC
}
//
~MyClass()
{
Dispose( false ); // GC
}
//
private void Dispose( bool manual)
{
if (! this .disposed)
{
if (manual)
{
// managed
//...
// - Dispose
// managed -
// Dispose,
// Dispose GC
}
// unmanaged
//...
disposed = true ;
}
}
}
* This source code was highlighted with Source Code Highlighter .
Moreover, a complex implementation exists in two versions. The first option offers MSDN on this link, and the second (to support inheritance) here on this one . The second implementation looks like this:public class Base: IDisposable
{
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
protected virtual void Dispose( bool disposing)
{
if (disposing)
{
// Dispose managed
}
// unmanaged
}
~Base()
{
Dispose ( false );
}
}
//
public class Derived: Base
{
protected override void Dispose( bool disposing)
{
if (disposing)
{
// Dispose managed
}
// unmanaged
// Dispose(bool)
base .Dispose(disposing);
}
// Dispose
// - .
}
* This source code was highlighted with Source Code Highlighter .
The difference, as is easy to see, is that the Dispose (bool) method has turned from closed to protected and virtual. Let's try to figure out why it is so difficult? And why is it necessary to know?using System;
namespace RSDN
{
public abstract class DisposableType: IDisposable
{
bool disposed = false ;
~DisposableType()
{
if (!disposed)
{
disposed = true ;
Dispose( false );
}
}
public void Dispose()
{
if (!disposed)
{
disposed = true ;
Dispose( true );
GC.SuppressFinalize( this );
}
}
public void Close()
{
Dispose();
}
protected virtual void Dispose( bool disposing)
{
if (disposing)
{
// managed objects
}
// unmanaged objects and resources
}
}
}
* This source code was highlighted with Source Code Highlighter .
Source: https://habr.com/ru/post/57432/
All Articles