How does the IDisposable interface work?

前端 未结 4 1709
谎友^
谎友^ 2021-01-17 20:01

I understand that it is used to deallocate unmanaged resources, however, I am confused as to when Dispose is actually called. I know it is called at the end of

4条回答
  •  再見小時候
    2021-01-17 20:32

    If you implement IDisposable correctly, you should also include a finalizer that will call Dispose() on your object.

    If you do that, it will get called by the GC. However, it's still a VERY good idea to try to always dispose of these objects yourself.

    The biggest problem with relying on the finalizer to call Dispose is that it will happen in another thread which you don't control. This can have nasty consequences in certain situations, including causing an exception that's happening in the GC thread, which is not good, as well as having a disposed field you check. This is also part of why including GC.SuppressFinalize(this) in your Dispose() method is important - once an object's disposed, you don't want to re-dispose it.

提交回复
热议问题