Prism Event Aggregation - subscriber not triggered

前端 未结 2 1273
萌比男神i
萌比男神i 2021-02-07 07:20

I\'m working on implementing an event aggregation with Prism. I have a few modules, and I want each of them to subscribe to events that tells them when they are requested. I sta

相关标签:
2条回答
  • 2021-02-07 07:31

    The Prism Event Aggregator uses Weak References to link to the events. This is to prevent memory leaks from event handlers.

    Once a module initializer has been run it's disposed of, so your event handler is being destroyed before the event is being fired. You can tell Prism to keep the event handler around by using an overload of Subscribe.

    evnt.Subscribe(MyModuleRequested, true);
    

    As a pattern, I tend to put any event subscribers in a separate class, and call that class from the modules Initialize method. That way the events stay alive but separate while the module is still destroyed.

    0 讨论(0)
  • 2021-02-07 07:36

    So, I just got a theory, but no time to test it right now.. Will do tomorrow.

    Question: Will adding modules to the ModuleCatalogue keep them alive? I assumed it would. Hence - the MyModule should stay alive - and then will be triggered when the event is published.

    protected override IModuleCatalog GetModuleCatalog()
    {
        var catalog = new ModuleCatalog();
        catalog.AddModule(typeof(MyModule));
        return catalog;
    }
    

    However, if this doesn't keep the module alive it is obvious that it will have a hard time respond to the event. The module-object dies, but it doesn't unsubscribe - hence I'll see the subscriber in the EventAggregator list, but the subscriber isn't around anymore. Also; I mentioned that I it does in fact work occasionally - which would be the case if the garbage collector didn't have time to take out the trash before the event is triggered.

    Does this sound like the case? If so - I haven't thought of a solution yet so you're welcome to suggest one in a different reply-thread..

    So; what is the ModuleCataloge anyway? Just a list kept for Initialization and then thrown away?

    0 讨论(0)
提交回复
热议问题