在Java中IDisposable的隐喻? [英] IDisposable metaphor in Java?

查看:674
本文介绍了在Java中IDisposable的隐喻?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个Java开发人员进入.NET我想了解IDisposable接口。可能有人请试图解释这个问题以及如何它不同于Java中会发生什么?谢谢你。

As a java developer getting into .NET I'd like to understand the IDisposable interface. Could somebody please try to explain this and how it differs from what happens in Java? Thanks.

推荐答案

我写了一个详细的一系列关于IDisposable的文章。

这里的基本思想是,有时你需要确定的处理资源。 IDisposable接口提供了机制。

The basic idea here is that sometimes you DO need deterministic disposal of resources. IDisposable provides that mechanism.

举例来说,假设你有一个窗口的控制。当这个被创建,它会创建一个窗口句柄(HWND)内部。当您从窗口中删除控制,它不再使用,控制变得符合垃圾收集 - 但它不会被收集的时候了。事实上,没有任何保障,如何长时间将它收集了。

For example, say you have a control in a Window. When this is created, it creates a windows handle (HWND) internally. When you remove the control from the Window, and its no longer used, the control becomes eligible for garbage collection - but it does not get collected right away. In fact, there are no guarantees as to how long it will be before it is collected.

直到GC运行并处理孤立的控制,它仍然会利用资源,因为它仍持有HWND。

Until the GC runs and processes the orphaned control, it will still use resources, since it's still holding the HWND.

的IDisposable提供了包含需要从GC清理分开做明确清理由对象的用户code对象的装置。在控制的情况下,我们可以调用 myControl.Dispose()这将立即用于控制同步清理本土资源(HWND)。

IDisposable provides a means for objects that contain code that needs cleanup separate from the GC to be explicitly cleaned up by the user of the object. In the control's case, we can call myControl.Dispose(), which will immediately, synchronously cleanup the "native" resources (HWND) used by the control.

这篇关于在Java中IDisposable的隐喻?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆