如何IDisposable接口的工作?

编程入门 行业动态 更新时间:2024-10-23 22:33:18
本文介绍了如何IDisposable接口的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

据我所知,它是用来释放非托管资源,但是,我很困惑,当处置实际上是调用。我知道它被称为在使用块的结束,但是当对象被垃圾回收也被调用?

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 a using block, but does it also get invoked when the object is garbage collected?

推荐答案

如果你正确地实现IDisposable,你应该还包括一个终结,将调用Dispose()在你的对象。

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

如果你这样做,它会被调用的GC。但是,它仍然是一个很不错的主意,试图永远处置这些对象的你自己。

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.

与依靠终结调用Dispose最大的问题是,它会在你不控制另一个线程发生。这可以在一定的情况下,讨厌的后果,包括引起异常发生的事情在GC线程,这是不好的,以及有一个处置场你检查。这也是为什么包括您的处置GC.Sup pressFinalize(本)的一部分()方法是很重要的 - 一旦对象的处置,你不想再处理它

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.

更多推荐

如何IDisposable接口的工作?

本文发布于:2023-11-04 05:32:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557082.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   工作   IDisposable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!