Implementing IDisposable in C#

This question already has an answer here:

  • Proper use of the IDisposable interface 18 answers

  • Dispose正在被调用,但它并没有做任何事情去销毁对象本身(你会注意到框架内的很多IDiposable类还有一个IsDisposed属性来表明非托管资源是否已经被释放)


    You are still able to access it because you defined it outside the scope of the using block and because you haven't set it to null.

    Note that using doesn't set the object to null, it simply means that your Dispose() method will be called, this gives you a contractually guaranteed way to dispose of any unmanaged resources that would otherwise not be cleaned up by the garbage collector.

    You should also consider the logic of your statement:

    I believe, using block automatically call dispose method. So, if I am create a new instance in using block, it would be dispose after existing using block.

    ... how could an object set it's own self to null?


    From MSDN

    IDisposable Interface

    Provides a mechanism for releasing unmanaged resources.

    The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams. Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.

    This is used for release umnamaged resources not for destroy object itself.

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

    上一篇: 处理文件路径跨平台

    下一篇: 在C#中实现IDisposable