What are finalisers for?

后端 未结 5 916
独厮守ぢ
独厮守ぢ 2021-01-17 23:16

I have been programming in .NET for four years (mostly C#) and I use IDiposable extensively, but I am yet to find a need for a finaliser. What are finalisers for?

5条回答
  •  难免孤独
    2021-01-17 23:39

    Finalizers are only for freeing unmanaged resources like GDI bitmap handles for example. If you don't allocate any unmanaged resources then you don't need finalizers. In general it's a bad idea to touch any managed object in a finalizer because the order of finalization is not guaranteed.

    One other useful technique using a finalizer is to assert that Dispose has been called when the application is required to do so. This can help catch coding errors in a DEBUG build:

    void Dispose()
    {
      GC.SuppressFinalize(this);
    }
    #if DEBUG
    ~MyClass()
    {
      Debug.Fail("Dispose was not called.");
    }
    #endif
    

提交回复
热议问题