Publish extensions

Aug 19, 2011 at 11:11 AM

Could anyone help me write methods that will do the following:

PublishOnCurrentThread, PublishOnBackgroundThread or PublishOnUIThreadAsync.

Thank you.

Aug 23, 2011 at 8:16 AM

Hello, anyone? Maybe some clue or something?

Sep 2, 2011 at 8:49 AM
Edited Sep 2, 2011 at 8:49 AM

What do you think about this:

 

	public static class EventAggregatorExtension {

		public static void PublishOnCurrentThread( this IEventAggregator eventAggregator, object message ) {
			eventAggregator.Publish( message, action => action() );
		}

		public static void PublishOnBackgroundThread( this IEventAggregator eventAggregator, object message ) {
			TaskEx.Run( () => eventAggregator.Publish( message, action => action() ) );
		}

		public static void PublishOnUIThreadAsync( this IEventAggregator eventAggregator, object message ) {
			Deployment.Current.Dispatcher.BeginInvoke( () => eventAggregator.Publish( message, action => action() ) );
		}

	}
Jan 18, 2013 at 6:53 AM

Thanks a lot awattar!!! Exactly what I was looking for :).

Best Regards 

Mar 18, 2013 at 8:02 PM
Edited Apr 5, 2013 at 5:51 PM
Now, with CM 1.5 it is even simpler:
/// <summary>
/// Extensions for <see cref="IEventAggregator"/>.
/// </summary>
public static class EventAggregatorExtensions {
    /// <summary>
    ///   Publishes a message on the current thread (synchrone).
    /// </summary>
    /// <param name="eventAggregator">The event aggregator.</param>
    /// <param name = "message">The message instance.</param>
    public static void PublishOnCurrentThread(this IEventAggregator eventAggregator, object message) {
        eventAggregator.Publish(message, action => action());
    }

    /// <summary>
    ///   Publishes a message on a background thread (async).
    /// </summary>
    /// <param name="eventAggregator">The event aggregator.</param>
    /// <param name = "message">The message instance.</param>
    public static void PublishOnBackgroundThread(this IEventAggregator eventAggregator, object message) {
#if !SILVERLIGHT || SL5 || WP8
        eventAggregator.Publish(message, action => System.Threading.Tasks.Task.Factory.StartNew(action));
#else
        eventAggregator.Publish(message, action => System.Threading.ThreadPool.QueueUserWorkItem(state => action()));
#endif
    }

    /// <summary>
    ///   Publishes a message on the UI thread asynchrone.
    /// </summary>
    /// <param name="eventAggregator">The event aggregator.</param>
    /// <param name = "message">The message instance.</param>
    public static void PublishOnUIThreadAsync(this IEventAggregator eventAggregator, object message) {
        eventAggregator.Publish(message, Execute.BeginOnUIThread);
    }
}