IDisposable metaphor in Java?

后端 未结 6 1234
滥情空心
滥情空心 2021-02-19 13:44

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?

6条回答
  •  太阳男子
    2021-02-19 14:24

    I wrote a detailed series of articles on IDisposable.

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

    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.

    Until the GC runs and processes the orphaned control, it will still use resources, since it's still holding the 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.

提交回复
热议问题