我想知道如果我们要处理一个持有非托管资源的对象,我们是否应该使用 dispose 和 finalize。 第二件事,如果我们处置一个对象,该对象是否仅在那一刻释放内存以及非托管资源,或者该对象的内存将在稍后由垃圾收集器释放。我想在 fianilize 上下文中知道同样的事情,一旦我们完成一个对象,就会在确定的时间为该对象释放内存,或者我们等到垃圾收集器释放它的内存。
最佳答案
您应该通过将对象的范围限制为 protected 来防止应用程序的用户直接调用对象的 Finalize 方法。此外,强烈建议您不要直接从应用程序代码中为基类以外的类调用 Finalize 方法。要正确处理非托管资源,建议您实现公共(public) Dispose 或 Close 方法,为对象执行必要的清理代码。 IDisposable 接口(interface)为实现该接口(interface)的资源类提供 Dispose 方法。因为它是公共(public)的,所以您的应用程序的用户可以直接调用 Dispose 方法来释放非托管资源使用的内存。当您正确实现 Dispose 方法时,Finalize 方法将成为在未调用 Dispose 方法的情况下清理资源的保障措施。
// Design pattern for a base class.
public class Base: IDisposable
{
private bool disposed = false;
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Free other state (managed objects).
}
// Free your own state (unmanaged objects).
// Set large fields to null.
disposed = true;
}
}
// Use C# destructor syntax for finalization code.
~Base()
{
// Simply call Dispose(false).
Dispose (false);
}
}
// Design pattern for a derived class.
public class Derived: Base
{
private bool disposed = false;
protected override void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Release managed resources.
}
// Release unmanaged resources.
// Set large fields to null.
// Call Dispose on your base class.
disposed = true;
}
base.Dispose(disposing);
}
// The derived class does not have a Finalize method
// or a Dispose method without parameters because it inherits
// them from the base class.
}
来源:MSND
关于c# - dispose vs finalize 对象如何释放内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21130750/