Strange behavior with actions, local variables and garbage collection in MVVM light Messenger

前端 未结 2 1814
别那么骄傲
别那么骄傲 2020-12-10 14:52

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:

2条回答
  •  醉话见心
    2020-12-10 15:20

    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...

提交回复
热议问题