如果对象没有 Finalizer,GC.SuppressFinalize() 是否有效?

Does GC.SuppressFinalize() have effect if the object has not Finalizer?

我知道因为某些版本 StreamWriter 停止支持终结器,但在 source code 中我看到它调用 GC.SuppressFinalize(this)。为什么叫它呢?我认为它实际上仅适用于具有 Finalizer 的对象。


更新

我想知道如果对象没有 Finalizer,GC.SuppressFinalize() 是否有一些效果?

它是 dispose pattern 的一部分。

Microsoft 将处置模式描述为:

public void Dispose()
{
   // Dispose of unmanaged resources.
   Dispose(true);
   // Suppress finalization.
   GC.SuppressFinalize(this);
}

引用 link:

The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object.Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.SuppressFinalize has no effect. Note that the actual cleanup is performed by the Dispose(bool) method overload.

编辑: 进一步看,关于 DRY,我会 StreamWriter.Close() 只是调用 StreamWrite.Dispose()。此外,StreamWriter.Close() 似乎是多余的,因为基础 class TextWriter.Close() 具有相同的内容! (而且那个应该直接调用 TextWrite.Dispose()。 但这只是 MHO。)