简体   繁体   中英

mvvmlight messenger strange behaviour

I have a strange behavior in my project. I use MvvmLight messenger to notify different parts of my UI to update.

   public EntryViewModel(MenuViewModel menuVM, Entry item)
    {
        this._menuVM = menuVM;
        OpenDetailsCommand = new RelayCommand(OpenDetailsInMainWindow);
        BackCommand = new RelayCommand(Back);

        this._entry = item;
        Refresh(); 

        Messenger.Default.Register<CardUpdateMessage>(this, this._entry.Id, msg => Refresh(); );   
 }

and send with

Messenger.Default.Send(new CardUpdateMessage(id), id);

when I see Messenger content after registration it contains about 400 registered actions of CardUpdateMessage, but when I call send none of them fires. By the way, similar code with single registered object per Message type work as I expect. What is the cause of this problem?

Update : I have made some research with debugger and found that in file https://mvvmlight.codeplex.com/SourceControl/latest#GalaSoft.MvvmLight/GalaSoft.MvvmLight (PCL)/Messaging/Messenger.cs method SendToList is fired and in its inner loop WeakAction is fired, but Refresh method is not run. Does it something I haven't suspected with WeakAction?

Solution : I have found the case of this issue. It's NOT ALLOWED to use anonimous function in Messenger.Register due to unexpected behavior. just Messenger.Default.Register(this, this._entry.Id, Refresh); and private void Refresh(CardUpdateMessage msg) ...

External reference : https://mvvmlight.codeplex.com/workitem/7640

This is the answer https://mvvmlight.codeplex.com/workitem/7640 and this Strange behavior with actions, local variables and garbage collection in MVVM light Messenger

Solution in short words - do no use lambdas in Messenger.Default.Register, because the can behave not as you expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM