What is the difference between using IDisposable vs a destructor in C#?

When would I implement IDispose on a class as opposed to a destructor? I read this article, but I'm still missing the point.

My assumption is that if I implement IDispose on an object, I can explicitly 'destruct' it as opposed to waiting for the garbage collector to do it. Is this correct?

Does that mean I should always explicitly call Dispose on an object? What are some common examples of this?


A finalizer (aka destructor) is part of garbage collection (GC) - it is indeterminate when (or even if) this happens, as GC mainly happens as a result of memory pressure (ie need more space). Finalizers are usually only used for cleaning up unmanaged resources, since managed resources will have their own collection/disposal.

Hence IDisposable is used to deterministically clean up objects, ie now. It doesn't collect the object's memory (that still belongs to GC) - but is used for example to close files, database connections, etc.

There are lots of previous topics on this:

  • deterministic finalization
  • disposing objects
  • using block
  • resources
  • Finally, note that it is not uncommon for an IDisposable object to also have a finalizer; in this case, Dispose() usually calls GC.SuppressFinalize(this) , meaning that GC doesn't run the finalizer - it simply throws the memory away (much cheaper). The finalizer still runs if you forget to Dispose() the object.


    The role of the Finalize() method is to ensure that a .NET object can clean up unmanaged resources when garbage collected . However, objects such as database connections or file handlers should be released as soon as possible, instead on relying on garbage collection. For that you should implement IDisposable interface, and release your resources in the Dispose() method.


    The only thing that should be in a C# destructor is this line:

    Dispose(False);
    

    That's it. Nothing else should ever be in that method.

    链接地址: http://www.djcxy.com/p/54498.html

    上一篇: 你如何防止IDisposable传播给你所有的课程?

    下一篇: 使用IDisposable与C#中的析构函数有什么区别?