Why call dispose(false) in the destructor?

前端 未结 6 1485
挽巷
挽巷 2020-12-12 11:33

What follows is a typical dispose pattern example:

 public bool IsDisposed { get; private set; }

  #region IDisposable Members

  public void Dispose()
  {
         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 12:24

    There are no destructors in C#. That's a Finalizer, which is a different thing.

    The distinction is whether you need to clean up managed objects or not. You don't want to try to clean them up in the finalizer, as they may themselves have been finalized.


    I just recently happened to look at the Destructors page of the C# Programming Guide. It shows that I was mistaken in my answer, above. In particular, there is a difference between destructor and finalizer:

    class Car
    {
        ~Car()  // destructor
        {
            // cleanup statements...
        }
    }
    

    is equivalent to

    protected override void Finalize()
    {
        try
        {
            // Cleanup statements...
        }
        finally
        {
            base.Finalize();
        }
    }
    

提交回复
热议问题