问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/39911423/mvvmlight-messenger-strange-behaviour