pub/sub: How to wait for all subscribers to complete

Topics: Prism v4 - WPF 4
Jan 26, 2015 at 5:38 AM
How can I wait for all subscribers to complete after a I publish an event before I continue execution to the next statement.

//wait for all subscribers to complete?
Jan 26, 2015 at 10:46 AM
Unless your subscribers are executing asynchronously, execution won't continue until all have completed. Your code should work just fine as is
Jan 26, 2015 at 3:33 PM
I have two publish events in a method. I want all the subscribers to finish the first publish before I call the second. None of the subscribers are being called while the method is executing. The first time a subscriber is called is after the method is completed. One way I can force the subscribers to get called after the first publish is by using Application.DoEvents(). But after reading about this online it says that we should not call this. Is there another way to achieve this?
Jan 27, 2015 at 8:41 PM
What you want is not possible without some other form of external locking based on the design of PubSubEvents (which I was directly part of). Events are supposed to be fire and forget from the publishers perspective. Because of the thread dispatching mechanisms of PubSubEvents that allows the subscriber to choose whether to handle the event on the publisher's thread (default), the UI thread, or a background thread, there is no way for the publisher to be sure if the subscriber has finished processing the event or not, nor in which order subscribers are notified.

If you want a more synchronous pub-sub like mechanism for something like you describe, I recommend using CompositeCommands. Those to have a pub-sub like semantic to them (you can register and unregister one or more loosely coupled handlers), but they have an imperative API to them - the "publisher" (command invoker) is explicitly saying "go do this now" and if multiple command handlers are registered, the Execute method will not return until all of the registered command handlers have been invoked and returned. There is no thread dispatching options with CompositeCommands.

There is still nothing stopping a handler from spinning up a separate thread in their handler for the command or handing it asynchronously with an async void Execute handler, but you at least get a guarantee of synchronous dispatch to the handler method start that you can't have (by design) with PubSubEvents.
Jan 27, 2015 at 8:47 PM
Thank you for the response