【问题标题】:Will this coding style result in a memory leak这种编码风格会导致内存泄漏吗
【发布时间】:2011-03-30 13:44:42
【问题描述】:

按照 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 会变得未被引用,从而成为垃圾回收的候选对象。

【问题讨论】:

    标签: c# silverlight event-handling mvvm-light


    【解决方案1】:

    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();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多