WPF/Multithreading: UI Dispatcher in MVVM

前端 未结 7 1380
有刺的猬
有刺的猬 2020-12-24 09:49

So say in an MVVM environment, I\'m in a background thread and I\'d like to run an update on a ui control. So normally I\'d go myButton.Dispatcher.BeginInvoke(blabla) but I

7条回答
  •  忘掉有多难
    2020-12-24 10:01

    From Caliburn Micro source code :

    public static class Execute
    {
        private static Action executor = action => action();
    
        /// 
        /// Initializes the framework using the current dispatcher.
        /// 
        public static void InitializeWithDispatcher()
        {
    #if SILVERLIGHT
            var dispatcher = Deployment.Current.Dispatcher;
    #else
            var dispatcher = Dispatcher.CurrentDispatcher;
    #endif
            executor = action =>{
                if(dispatcher.CheckAccess())
                    action();
                else dispatcher.BeginInvoke(action);
            };
        }
    
        /// 
        /// Executes the action on the UI thread.
        /// 
        /// The action to execute.
        public static void OnUIThread(this System.Action action)
        {
            executor(action);
        }
    }
    

    Before using it you'll have to call Execute.InitializeWithDispatcher() from the UI thread then you can use it like this Execute.OnUIThread(()=>SomeMethod())

提交回复
热议问题