What are the rules for when dispose() is required?

前端 未结 4 1358
清歌不尽
清歌不尽 2021-01-13 08:46

Although I have been coding for some time, I\'m really just barely into what I would call an intermediate level coder. So I understand the principle of dispose(), which is

4条回答
  •  悲&欢浪女
    2021-01-13 09:21

    If you have an object that implements IDisposable then you must always explicitly call .Dispose() on that object. If it doesn't implement IDisposable then obviously you don't call .Dispose() because you can't.

    If you are writing your own objects then the rule as to whether or not to implement IDisposable is simply this: If your object holds references to unmanaged objects OR if it holds references to objects that implement IDisposable then it must implement IDisposable.

    The GC never calls .Dispose() for you. You must always do it - either directly or through a finalizer.

    The GC may (most likely, but not always) call a finalizer, so you can write a finalizer to call dispose, but be careful that you implement the disposable pattern correctly, and be certain that you understand that the finalizer may not ever run so if your dispose method does something vitally important it might be better to call .Dispose() directly before you lose the reference to the object.

提交回复
热议问题