Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM Light Messenger executing multiple times

Tags:

mvvm-light

I am using MVVM Light and am using Messages to communicate between ViewModels to let a ViewModel know when it is ok to execute something. My problem is that I register for a message and then it receives it multiple times. so to keep from my program executing something more than once I have to create boolean flags to see if it has already been recieved. Any idea why it does this and how I can stop it?

like image 831
Jason Avatar asked Sep 13 '10 15:09

Jason


2 Answers

Make sure you unregister your message handlers once you do not need them anymore. The Messenger keeps a reference to the registered methods and this prevents them from being garbage collected.

Therefore, for ViewModels: make sure that you call Cleanup once you done (or implement IDisposable and call Cleanup from there).

For Views (Controls, Windows, or similar) call Messenger.Unregister in an event that occurs on the teardown of the view, e.g. the Unloaded event.

This is a known behaviour of the MVVM and has been discussed in several places.

like image 60
AxelEckenberger Avatar answered Nov 14 '22 12:11

AxelEckenberger


Very old question but I solved the problem by doing this:

static bool isRegistered = false;

and then, in the constructor:

if( !isRegistered )
{
   Messenger.Default.Register<MyMessage>(this, OnMessageReceived);
   isRegisterd = true;
}
like image 35
jcgalveza Avatar answered Nov 14 '22 10:11

jcgalveza