EventAggregator and Cancellable events

Topics: Prism v1, Prism v2 - Silverlight 2, Prism v2 - Silverlight 3, Prism v2 - WPF 3.5
Jul 23, 2009 at 4:08 PM

Hi there,

We're using the EventAggregator in our WinForms application and I've come across a situation where I think it makes sense to use EventAggregator (over a Command).  We have a central "context" class that manages all loaded objects associated with a given context (a Customer, in this case).  As objects are loaded, they are added to the context and then when we save, we save all loaded objects in the context. 

During the save, I want to add an event (ContextSaving?) that subscribers can catch and opt to cancel if they deem it necessary (similar to cancellable events in Windows Forms like the Form's Closing event). 


Question: have others done this before?  Is this a gross violation of the EventAggregator concept?  

Jul 24, 2009 at 6:50 PM

Hi Jeremy, 

It's great that you have been able to use the prism EventAggregator in a Winforms app! You might find Glenn Block's  post on Bringing Prism to WinForms useful. 

Back to your question. If I understood your scenario correctly, you need to have an operation (in this case saving) which can be canceled by decoupled entities. If this is the case, there is no out-of-the-box cancellable event in prism. Nevertheless, as you said, you might implement a similar approach to winform's cancellable events by adding an Cancelled property to the event payload: When an event is published by the EventAggregator, the same instance of the payload is used for all subscribed handlers. So you can set a property that indicates that the action should not be executed.

The following pseudo code could be used: 

In the Subscribers: 

public void OnContextSaving(SavingEventArg e)
                               e.Canceled = true;

In the publisher:

savingEventArg.Canceled = false;
                // Do Saving

for this approach to work properly you need to subscribe using the default thread option (ThreadOption.PublisherThread )

There was a similar discussion on the SCSF about cancelling events. It's a different scanario, but same concepts might apply:

 In the prism discussion there also another discussion that might be related (though not using eventAggregator):


Hope it helps! 

Matias Bonaventura