//Free managed resources too, but only if i'm being called from Dispose //(If i'm being called from Finalize then the objects might not exist //anymore if (freeManagedObjectsAlso) { if (this.databaseConnection != null) { this.databaseConnection.Dispose(); this.databaseConnection = null; } if (this.frameBufferImage != null) { this.frameBufferImage.Dispose(); this.frameBufferImage = null; } } }
所以我们先前写的Dispose函数变成了这样:
1 2 3 4 5 6 7 8 9
public void Dispose() { Dispose(true); //i am calling you from Dispose, it's safe }
public ~MyObject() { Dispose(false); //i am *not* calling you from Dispose, it's *not* safe }
提醒一下,如果我们的类的父类也是IDisposable的,我们需要调用父类的Dispose函数。
1 2 3 4 5 6 7 8 9 10 11
public Dispose() { try { Dispose(true); //true: safe to free managed resources } finally { base.Dispose(); } }
public void Dispose() { Dispose(true); //i am calling you from Dispose, it's safe GC.SuppressFinalize(this); //Hey, GC: don't bother calling finalize later }