What are finalisers for?

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

    Wikipedia says:

    ...a finalizer is a piece of code that ensures that certain necessary actions are taken when an acquired resource... is no longer being used [because the owning object has been garbage collected]

    And if you're not using a finaliser when you're writing IDisposables you've quite possibly got memory leaks, because there's no guarantee an owner is actually going to call Dispose().

    MS themselves recommend you write something similar to this into your implementers:

        public void Dispose()
        {
            this.Dispose(true);
        }
    
        protected virtual void Dispose(bool disposing)
        {
            if (!this.isDisposed)
            {
                if (disposing)
                {
                    GC.SuppressFinalize(this);
                }
            }
            //Dispose of resources here
            this.isDisposed = true;
        }
    
        ~DisposableSafe()
        {
            this.Dispose(false);
        }
    
        private bool isDisposed = false;
    

    Personally, I can't stand the copy-paste so I tend to wrap that in an abstract class for reuse.

提交回复
热议问题