MVVM – Environment – MGDispatchingWorker

In the MVVM pattern I always need the same base structure of the DispatchingWorker.
This class is located between the ViewModel and the Worker. It is responsible for running the actions in the right thread.

And this class has always the same base structure. So I decided to create my own base class which I can easily extend.

Well here is the result. It just contains a few necessary methods to run actions in the GUI-Thread or in a new Worker Thread.

    /// <summary>
    /// This class can be used as a base for the DispatchingWorker of the MVVM Pattern
    /// It contains a few util methods which help to run methods in Threads or to do Actions in the GUI-Thread
    /// </summary>
    public class MGDispatchingWorker
    {
        public DispatchingWorker()
        {
            _currentDispatcher = Dispatcher.CurrentDispatcher;
        }

        #region Field

        private readonly Dispatcher _currentDispatcher;

        #endregion

        #region UtilMethods

        /// <summary>
        /// This method runs the given action in a new thread (not GUI-Thread)
        /// </summary>
        /// <param name="action">The action which should be run in a new Thread</param>
        protected void DoThreadedAction(Action action)
        {
            var thread = new Thread(action.Invoke);
            thread.Start();
        }

        /// <summary>
        /// This method executes the given action in the GUI-Thread
        /// </summary>
        /// <param name="action">The action which should be executed in the GUI-Thread</param>
        protected void DoDispatchedAction(Action action)
        {
            if (_currentDispatcher.CheckAccess())
                action.Invoke();
            else
                _currentDispatcher.Invoke(action);
        }

        /// <summary>
        /// This method executed the given action asynchronous in the GUI-Thread
        /// </summary>
        /// <param name="action">The action which should be executed asynchronous in the GUI-Thread</param>
        protected void DoDispatchedActionAsync(Action action)
        {
            if (_currentDispatcher.CheckAccess())
                action.Invoke();
            else
                _currentDispatcher.BeginInvoke(action);
        }

        #endregion
    }
Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: