没什么,WithEvents就字段和内存泄漏字段、没什么、内存、WithEvents

2023-09-07 00:20:35 作者:凉情

是否有必要设置为没有(在Dispose()方法)均 WithEvents就字段?

显然手柄关键字将添加处理程序等领域,但不会删除它,直到这个领域是不是没有,这样就可以产生内存泄漏?!

这应该是对案件特别实际的像

 类Foo
{
    私人WithEvents就_bar,酒吧

    公共子新(BYVAL酒吧,酒吧)
        _bar =酒吧
    结束小组

    私人小组Bar_Changed(BYVAL发件人为对象,_
        BYVALË作为EventArgs的)把手_bar.Changed
    '...'
    结束小组
}
 

解决方案 内存泄漏检测

这会产生内存泄漏,如果到你订阅的目标住长于用户。在大多数情况下,这是不正确的。

取的WinForms的实例。通常情况下,你看到一个WinForm程序上控制 WithEvents就修改。外表格类订阅并响应这些事件。这不会导致内存泄漏,但因为该项目为您订阅的控制情况下,有大致相同的寿命为订户,

在那里的寿命也不同,那么是的,字段设置为没有的情况下将导致你从事件和prevent退订可能存在内存泄漏。

Is it necessary to set to Nothing(in Dispose()) all WithEvents fields?

Apparently Handles keyword adds handlers to such fields, but does not remove it until this field is not Nothing, and this can generate memory leaks?!.

This should be specially actual on cases like

class Foo
{
    Private WithEvents _bar as Bar

    Public Sub New(ByVal bar as Bar)
        _bar = bar
    End Sub

    Private Sub Bar_Changed(ByVal sender as Object, _ 
        ByVal e as EventArgs) Handles _bar.Changed
    '...  '
    End Sub
}

解决方案

This can generate memory leaks if the object to which you are subscribed lives longer than the subscriber. In the majority of cases this is not true.

Take WinForms for instance. Typically you see the WithEvents modifier on controls in a WinForm application. The outer Form class subscribes and reacts to these events. This does not cause a memory leak though because the item to which you are subscribed, the Control instances, have roughly the same lifetime as the subscriber, the Form.

In the case where the lifetimes do differ then yes, setting the field to Nothing will cause you to unsubscribe from the event and prevent a possible memory leak.