这种编码风格会导致内存泄漏吗

发布于 2024-10-28 06:00:47 字数 593 浏览 1 评论 0原文

按照 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丘比特射中我 2024-11-04 06:00:47

editWindow 将保留对 this 的引用,但没有任何东西会引用 editWindow,因此它最终会被垃圾收集,并且对this 将被丢弃。所以它不应该导致任何内存泄漏...

如果你想确保不会有问题,你可以取消订阅该事件:

InitializeComponent();
Messenger.Default.Register<EditorInfo>(this, (editorData) =>
{
    ChildWindow editWindow = new EditWindow();
    EventHandler handler = (s, args) =>
    {
        editWindow.Closed -= handler;
        if (editWindow.DialogResult == true)
            // Send data back to VM
        else
           // Send 'Cancel' back to VM
   };

   editWindow.Closed += handler;

   editWindow.Show();
});

editWindow will keep a reference to this, but nothing will have a reference to editWindow, so it will eventually be garbage collected, and the reference to this 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:

InitializeComponent();
Messenger.Default.Register<EditorInfo>(this, (editorData) =>
{
    ChildWindow editWindow = new EditWindow();
    EventHandler handler = (s, args) =>
    {
        editWindow.Closed -= handler;
        if (editWindow.DialogResult == true)
            // Send data back to VM
        else
           // Send 'Cancel' back to VM
   };

   editWindow.Closed += handler;

   editWindow.Show();
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文