Why does the traditional Dispose pattern suppress finalize?

后端 未结 6 1138
渐次进展
渐次进展 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:57

    The IDisposable pattern is used so that the object can clean up its resources deterministically, at the point when the Dispose method is called by the client code.

    The finaliser is only there as a fallback in case the client code fails to call Dispose for some reason.

    If the client code calls Dispose then the clean-up of resources is performed there-and-then and doesn't need to be done again during finalisation. Calling SuppressFinalize in this situation means that the object no longer incurs the extra GC cost of finalisation.

    And, if your own class only uses managed resources then a finaliser is completely unnecessary: The GC will take care of any managed resources, let those resources themselves worry about whether they need a fallback finaliser. You should only consider a finaliser in your own class if it directly handles unmanaged resources.

提交回复
热议问题