这种编码风格会导致内存泄漏吗
按照 MVVM 模式,我尝试通过视图连接子窗口的显示,以响应视图模型的请求。
使用 MVVM-Light Messenger,视图将在视图的构造函数中注册显示子窗口的请求,如下所示:
InitializeComponent();
Messenger.Default.Register<EditorInfo>(this, (editorData) =>
{
ChildWindow editWindow = new EditWindow();
editWindow.Closed += (s, args) =>
{
if (editWindow.DialogResult == true)
// Send data back to VM
else
// Send 'Cancel' back to VM
};
editWindow.Show();
});
使用 Lambda 订阅 ChildWindow Closed 事件是否会导致垃圾收集问题。或者换句话说,什么时候(如果有的话)editWindow 会变得未被引用,从而成为垃圾回收的候选对象。
Following the MVVM pattern I'm trying to wire up the display of a child window by the View in response to a request from the View Model.
Using the MVVM-Light Messenger the View will Register for the request to display the child window in the constructor of the View as so:
InitializeComponent();
Messenger.Default.Register<EditorInfo>(this, (editorData) =>
{
ChildWindow editWindow = new EditWindow();
editWindow.Closed += (s, args) =>
{
if (editWindow.DialogResult == true)
// Send data back to VM
else
// Send 'Cancel' back to VM
};
editWindow.Show();
});
Does subscribing to the ChildWindow Closed event using a Lambda cause problems for garbage collection. Or put it another way, when (if ever) will the editWindow become unreferenced and so a candidate for garbage collection.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
editWindow
将保留对this
的引用,但没有任何东西会引用editWindow
,因此它最终会被垃圾收集,并且对this
将被丢弃。所以它不应该导致任何内存泄漏...如果你想确保不会有问题,你可以取消订阅该事件:
editWindow
will keep a reference tothis
, but nothing will have a reference toeditWindow
, so it will eventually be garbage collected, and the reference tothis
will be discarded. So it shouldn't cause any memory leak...If you want to be sure there will be no problem, you can unsubscribe from the event: