【问题标题】:MVVM Light Threading ExampleMVVM 轻线程示例
【发布时间】:2010-11-17 05:30:08
【问题描述】:

有没有关于如何使用 MVVM Light 的线程部分的示例?使用 MVVMLight.threading 与普通 .net 线程相比有什么优势?

【问题讨论】:

    标签: wpf mvvm-light wpf-4.0


    【解决方案1】:

    看起来 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;
    
        }
    }
    

    }

    仅此而已。根据静态 App 构造函数 (wpf) 或 Application_Startup 事件处理程序 (Silverlight) 中的注释使用 DispatcherHelper.Initialize() - 然后您可以使用 DispatcherHelper.CheckBeginInvokeOnUI(Action action)

    问候

    【讨论】:

    • 谢谢代理。它与普通的 .net 线程相比如何?它可以在视图模型中使用吗?
    • 1.首先你初始化 DispatcherHelper 类调用 Initialize() 方法 - 你必须在 ui 线程上执行它,以便它可以记住/设置其对调度程序的私有引用
    • 2.之后你可以使用 DispatcherHelper.CheckBeginInvokeOnUI(Action action) - 从你想要的任何地方 - 视图、模型、视图模型 - 它总是使用 ui 线程来调用你的操作 3. 关于正常的 .net 线程比较 - 通常你必须自己做这些事情:保持对 ui 调度程序的引用,检查你是否在 ui 线程上,最后调用 dispatcher.BeginInvoke(action) - 使用这个类更容易
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多