开发者

MVVM Light Threading Example

开发者 https://www.devze.com 2023-01-25 17:38 出处:网络
Are there any examples on how to use the Threading portion of MVVM Light? What is the advantage of using the MVVMLight开发者_StackOverflow社区.threading over normal .net threading?looks like all threa

Are there any examples on how to use the Threading portion of MVVM Light? What is the advantage of using the MVVMLight开发者_StackOverflow社区.threading over normal .net threading?


looks like all threading portion in mvvmlight is this class :

public static class DispatcherHelper
{

    public static Dispatcher UIDispatcher
    {
        get;
        private set;
    }

    /// <summary>
    /// Executes an action on the UI thread. If this method is called
    /// from the UI thread, the action is executed immendiately. If the
    /// method is called from another thread, the action will be enqueued
    /// on the UI thread's dispatcher and executed asynchronously.
    /// <para>For additional operations on the UI thread, you can get a
    /// reference to the UI thread's dispatcher thanks to the property
    /// <see cref="UIDispatcher" /></para>.
    /// </summary>
    /// <param name="action">The action that will be executed on the UI
    /// thread.</param>
    public static void CheckBeginInvokeOnUI(Action action)
    {
        if (UIDispatcher.CheckAccess())
        {
            action();
        }
        else
        {
            UIDispatcher.BeginInvoke(action);
        }
    }

    /// <summary>
    /// This method should be called once on the UI thread to ensure that
    /// the <see cref="UIDispatcher" /> property is initialized.
    /// <para>In a Silverlight application, call this method in the
    /// Application_Startup event handler, after the MainPage is constructed.</para>
    /// <para>In WPF, call this method on the static App() constructor.</para>
    /// </summary>
    public static void Initialize()
    {
        if (UIDispatcher != null)
        {
            return;
        }

        // for silverlight
        UIDispatcher = Deployment.Current.Dispatcher;

        // wpf
        //IDispatcher = Dispatcher.CurrentDispatcher;

    }
}

}

and that's all. Use DispatcherHelper.Initialize() according to comment in static App constructor (wpf) or Application_Startup event handler (Silverlight) - and then u can use DispatcherHelper.CheckBeginInvokeOnUI(Action action)

Regards

0

精彩评论

暂无评论...
验证码 换一张
取 消