.net 中的 Finalize 和 Dispose 有什么区别?

发布于 2024-09-17 05:32:59 字数 282 浏览 5 评论 0原文

可能的重复:
完成与处置

大家好,

最近我在一次采访中被问到有关 Finalize 和 Dispose 的问题。它们分别何时使用以及垃圾收集器与它们有何关系。请分享链接以了解有关该主题的更多信息。

请分享...

提前致谢。

Possible Duplicate:
Finalize vs Dispose

Hi,

Recently I was quizzed in an interview about finalize and dispose. When is each one of them used and how is Garbage Collector related to them. Kindly share links to enlighten more on the topic.

Kindly share ...

Thanks in advance.

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

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

发布评论

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

评论(2

淡紫姑娘! 2024-09-24 05:32:59

垃圾回收在符合条件的对象之前运行终结器用于收集被回收。 Dispose() 用于清理非托管资源,例如网络连接、文件、操作系统内容的句柄等。它与 using 块结合使用效果最佳,编译器确保在完成对象处理后立即调用 Dispose() – 并且还确保您不能一旦对象被处理掉,就可以不再使用该对象。

请注意,终结器不必 run,所以依赖它可能是危险的:

这对您意味着什么:您的程序不能依赖终结器来保持整洁。终结器是一个安全网,而不是资源回收的主要手段。当您使用完资源后,您需要通过调用 Close 或 Disconnect 或对象上可用的任何清理方法来释放它。 (IDisposable 接口规范了此约定。)

还要注意对象符合收集条件的精确时间。阅读上面链接的文章 - 它既不是范围(一个奇怪的词,与对象的生命周期无关 - 它是 “合法的程序文本区域通过其非限定名称引用[命名实体]。”)也不是严格的引用计数,因为即使在对它的最后一个引用消失之前,对象也可以成为符合收集条件的对象。

Finalizers are run by the Garbage Collection before an object that is eligible for collection is reclaimed. Dispose() is meant for cleaning up unmanaged resources, like network connections, files, handles to OS stuff, &c. It works best in conjunction with the using block where the compiler makes sure that Dispose() will be called immediately once you are done with an object – and also ensures that you cannot work with the object anymore once it's disposed.

Note that finalizers don't have to run, so relying on that can be dangerous:

What this means for you: Your programs cannot rely on finalizers keeping things tidy. Finalizers are a safety net, not a primary means for resource reclamation. When you are finished with a resource, you need to release it by calling Close or Disconnect or whatever cleanup method is available on the object. (The IDisposable interface codifies this convention.)

Careful also with the precise time when an object becomes eligible for collection. Read the article linked above – it's neither scope (a weird word which has noting to do with the lifetime of an object – it's “the region of program text in which it is legal to refer to [a named entity] by its unqualified name.”) nor is it strictly reference counting as an object can become eligible for collection even before the last reference to it goes away.

放血 2024-09-24 05:32:59
  1. Finalize:不确定性非确定性析构函数/终结器调用当不再有对此实例的引用时,垃圾收集器会自动执行此操作。
  2. Dispose:由开发人员在实现 IDisposable 的对象上确定性调用免费资源。
  1. Finalize: undeterministic nondeterministic destructor/finalizer called automatically by the Garbage Collector when there are no more references to this instance.
  2. Dispose: deterministically called by the developer on an object implementing IDisposable to free resources.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文