What are finalisers for?

后端 未结 5 913
独厮守ぢ
独厮守ぢ 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:56

    A finalizer is a last ditch attempt to ensure that something is cleaned up correctly, and is usually reserved for objects that wrap unmanaged resources, such as unmanaged handles etc that won't get garbage collected.

    It is rare indeed to write a finalizer. Fortunately (and unlike IDisposable), finalizers don't need to be propagated; so if you have a ClassA with a finalizer, and a ClassB which wraps ClassA, then ClassB does not need a finalizer - but quite likely both ClassA and ClassB would implement IDisposable.

    For managed code, IDisposable is usually sufficient. Even if you don't clean up correctly, eventually the managed objects will get collected (assuming they are released).

提交回复
热议问题