Search code examples
.netwpfprismprism-4

Prism CompositeEvent not fired with anonymous filter delegate specified by helper class


I have a TestEvent class as mentioned below:

class TestEvent: CompositePresentationEvent<object>
    {
        public void Subscribe(Action<object> action, int number)
        {
            this.Subscribe(action, ThreadOption.PublisherThread, false, arg=>arg.Equals(number));
        }
    }

If I subscribe to the event like so:

eventAggregator.GetEvent<TestEvent>().Subscribe(_=>MessageBox.Show("Hi"), 3);

The event is not fired. However if I subscribe it like so:

eventAggregator.GetEvent<TestEvent>().Subscribe(_ => MessageBox.Show("Hi"), ThreadOption.PublisherThread, false, arg => arg.Equals(3));

It 'does' fire. Though conceptually, syntactically and logically both are similar. The only difference is that the first one uses the helper method in the event class to subscribe to the event.

I'm sure this is something related to weak reference to delegate that is kept by the CompositeEvent class because the first one works if I set keepSubscriberAlive=true (third argument) in the subscribe call. I can't just go with that solution because I don't know what is that it will keep alive? will it be the class that subscribed to the event? If so then the class is alive even without passing false then why is that the event is not fired/handled in first case?

Can anyone explain this behavior?


Solution

  • In the first example the code captures a variable, passed to the TestEvent's method. In this case, compiler needs to create a class that wraps the number. A new instance of this class should be instantiated every time when the TestEvent's Subscribe is called.

    In the second example there is no data to capture, so the delegate which is passed to the Subscribe can be made static. In this case it will live before domain unloading.