没什么,WithEvents就字段和内存泄漏 [英] Nothing, WithEvents Fields and Memory Leaks
问题描述
是否有必要设置为没有
(在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.
这篇关于没什么,WithEvents就字段和内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!