MVVM Light Listener not releasing / deterministic

2019-01-26 16:33发布

I have a childwindow with an associated VM that gets created each time I ask the child window to open. when the childwindow opens, it registers a listener for an MVVM Light message. After I close the window, I'm pretty sure that I'm releasing all references to it, but I don't actually call dispose because it does not implement IDisposeable.

When I instanciate another child window of the same type, and send it a different context, I know that I'm receiving the message from the previous instanciation of the VM... each time I use the window, more and more VM are listening, and the code repeats.

How can I be sure that my previous VM that registered to listen to a message, has actually been released and is no longer active. Is there a deterministic way to do this?

标签: mvvm-light
3条回答
▲ chillily
2楼-- · 2019-01-26 16:51

You can use either the Cleanup method or manually unregister the message. For more details click here.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-26 17:08

Whenever you register a message you should make sure that you unregister the message as well. To unregister you can use Cleanup method on classes deriving from ViewModelBase. In other cases, e.g. a view, you should implement a method hat is called when the view is unloaded - e.g by trapping and handling the unloaded event on a control or view. In this method you then call Messenger.Unregister(EventTarget).

This behaviour is a quirk in the current version of the toolkit, and Laurent is aware of it.

查看更多
Emotional °昔
4楼-- · 2019-01-26 17:12

How have you coded the handler for the message in the VM? It sounds like you're probably pointing it to a method inside the same VM which is registering for the message. This causes the Messenger class to maintain a reference to the VM and prevent it's garbage collection (see here for discussion). There are two solutions: implement IDisposable and unregister all messages for your VM instance or simply unregister all messages from the VM instance when the child dialog closes. Personally I'd do both to ensure the entire object web is released.

查看更多
登录 后发表回答