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

Ral*_*ton 6 c# silverlight event-handling mvvm-light

在MVVM模式之后,我试图通过View连接子窗口的显示以响应来自View Model的请求.

使用MVVM-Light Messenger,View将注册请求以在View的构造函数中显示子窗口,如下所示:

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();
});
Run Code Online (Sandbox Code Playgroud)

使用Lambda订阅ChildWindow Closed事件会导致垃圾回收问题.或者换句话说,当(如果有的话)editWindow将被取消引用并因此成为垃圾收集的候选者时.

Tho*_*que 4

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();
});
Run Code Online (Sandbox Code Playgroud)