Why do we need parameter disposing in the below code snippet.
Moreover we invoke dispose with false, in finalizer and it won't release or do the clean up.
So what if dispose never get called?
Isn't dispose always get called before finalizer?
using System;
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
**//Do we really need this condition?
if (disposing)**
{
// called via myClass.Dispose().
// OK to use any private object references
}
disposed = true;
}
}
public void Dispose()
// Implement IDisposable
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass() // the finalizer
{
//why do we need to call with false?
Dispose(false);
}
}
In other words, why not?
using System;
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool suppressFinalize)
{
if (!disposed)
{
//Do we really need this condition?
// called via myClass.Dispose().
// OK to use any private object references
disposed = true;
}
if (!suppressFinalize)
{
GC.SuppressFinalize(this);
}
}
public void Dispose()
// Implement IDisposable
{
Dispose(true);
}
~MyClass() // the finalizer
{
//why do we need to call with false?
Dispose(false);
}
}
In fact, do I really need finalizer? Why not this?
using System;
public class MyClass : IDisposable
{
public void Dispose()
// Implement IDisposable
{
//just do the cleanup and release resources
GC.SuppressFinalize(this);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…