为什么“Finalize 方法不应引用任何其他对象”?

发布于 2024-08-30 00:04:34 字数 364 浏览 7 评论 0原文

我一直在思考为什么建议我们不应该在 Finalize 中释放托管资源。 如果您在 http://msdn.microsoft 上看到代码示例。 com/en-us/library/system.gc.suppressfinalize.aspx ,并搜索字符串“Dispose(bool disducing)在两个不同的场景中执行”并阅读该评论,您就会明白我的意思。

我能想到的唯一可能性是,它可能与无法预测何时调用终结器这一事实有关。 有谁知道正确答案吗?

谢谢, 米沙尔

I have been pondering why it is recommended that we should not release managed resources inside finalize.
If you see the code example at http://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx , and search for string "Dispose(bool disposing) executes in two distinct scenarios" and read that comment, you will understand what I mean.

Only possibility I can think of is that it probably has something to do with the fact that it is not possible to predict when finalizer will get called.
Does anyone know the right answer ?

thanks,
mishal

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如歌彻婉言 2024-09-06 00:04:34

如果您从终结器引用另一个对象,则您不知道该对象是否已被终结,以及如果它被终结,它将如何表现。 (我不知道当前的 CLR 是否运行多个终结器线程,但另一个可怕的可能性是,当终结器运行时,它正在被终结。)

在终结器中,您需要做的就是释放您拥有的非托管资源直接地。如果您引用拥有资源的其他托管类型,请让它们在终结器中完成其工作。

If you're referencing another object from the finalizer, you don't know if that object has already been finalized - and how it will behave if it is finalized. (I don't know whether any current CLR runs multiple finalizer threads, but another scary possibility is that it's in the process of being finalized when your finalizer runs.)

All you should need to do in a finalizer is release unmanaged resources that you own directly. If you're referencing other managed types which own resources, let them do their job in their finalizers.

平生欢 2024-09-06 00:04:34

我认为你已经说到点子上了。如果您查看 Object.Finalize 文档,它说:请参阅 IDisposable 接口,以获取一种补充且更可控的资源处置方式。“补充”的意思是“另一种方法”,并且是可控的……正是您所说的。

编辑:还有乔恩·斯基特所说的。多个终结器线程的概念确保我今晚要么睡不着,要么做噩梦。

I think you've pretty much hit the nail on the head. If you look at the wording in the Object.Finalize documentation, it says: See the IDisposable interface for a complementary and more controllable means of disposing resources. "Complementary" meaning, "another way to do it," and controllable being..exactly what you said.

Edit: And what Jon Skeet said. The notion of multiple finalizer threads has ensured I will either not be sleeping, or having very bad dreams tonight.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文