Dispoable pattern with c#4.0 & vs2010 [duplicate]
Possible Duplicate:
C# Finalize/Dispose pattern
How should I go about implementing disposable pattern (IDisposable interface) properly with vs2010 and c#4? A quick example and and important tip would be so nice.
I know there are c#2 examples but asking more for c#4.
Edit: Alright please delete开发者_运维知识库 the question (as I cant). I now see that nothing with respect to object disposal have changed since c#2.0 to 4.0
The same way as in previous versions of C#. The recommended pattern goes along those lines:
class MyClass : IDisposable
{
~MyClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Dispose managed resources
}
// Dispose unmanaged resources
disposed = true;
}
}
}
See this MSDN page for details.
The basic pattern.
/// <summary>
/// Dispose Method
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Deconstructor
/// </summary>
~[PutYourClassHere]()
{
Dispose(false);
}
/// <summary>
/// IDisposable Implementation
/// </summary>
/// <param name="disposing">Disposing Flag</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
//Free Managed Resources
}
//Free Native Resources
}
精彩评论