I am having a really strange problem with the Messenger system in MVVM Light. It\'s hard to explain, so here is small program that demonstrates the issue:
I agree, the behavior of this program is really strange.
I tried it myself and as you already figured out the problem is somehow related to this line:
var x = target;
I have no idea why this line causes any trouble but you might consider this workaround:
class Program
{
static void Main(string[] args)
{
var prog = new Program();
var recipient = new object();
prog.RegisterMessageA(recipient);
prog.RegisterMessageB(recipient);
prog.SendMessage("First Message");
GC.Collect();
prog.SendMessage("Second Message");
}
public void RegisterMessageA(object target)
{
Messenger.Default.Register(target, (Message msg) =>
{
Console.WriteLine(msg.Name + " received by A");
var x = msg.Target;
});
}
public void RegisterMessageB(object target)
{
Messenger.Default.Register(target, (Message msg) =>
{
Console.WriteLine(msg.Name + " received by B");
});
}
public void SendMessage(string name)
{
Messenger.Default.Send(new Message { Name = name });
}
class Message : MessageBase //part of the MVVM Light framework
{
public string Name { get; set; }
}
}
MessageBase is a class from the MVVM Light Framework which offers the possibility to retrieve the target from the message itself.
But I'm not sure if this is what you're trying to achieve...