MVVM Light Threading示例

时间:2010-11-17 05:30:08

标签: wpf mvvm-light wpf-4.0

有没有关于如何使用MVVM Light的线程部分的例子?使用MVVMLight.threading比正常的.net线程有什么好处?

1 个答案:

答案 0 :(得分:3)

看起来mvvmlight中的所有线程部分都是这个类:

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;

    }
}

}

就是这样。根据静态应用程序构造函数(wpf)或Application_Startup事件处理程序(Silverlight)中的注释使用DispatcherHelper.Initialize() - 然后你可以使用DispatcherHelper.CheckBeginInvokeOnUI(Action action)

此致