Why does the traditional Dispose pattern suppress finalize?

后端 未结 6 1183
渐次进展
渐次进展 2021-01-17 22:10

Assuming this as the traditional Dispose pattern (taken from devx but seen on many websites)

class Test : IDisposable
{
  private bool isDisposed = false;

          


        
6条回答
  •  没有蜡笔的小新
    2021-01-17 22:54

    From Msdn : " This method sets a bit in the object header, which the system checks when calling finalizers. The obj parameter is required to be the caller of this method. Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it. "

    So it prevents an extra call from the GC. If it is called from within the the finalizer method, when object is being finalized, then it wont do anything, as it is already being finalised. Otherwise, the GC is allowed to reclaim memory, without finalisation of the object, thus making things faster.

提交回复
热议问题