DispatcherHelper

 /// 
    /// 使用之前在App.Config中初始化Initialize()
    /// 
    public static class DispatcherHelper
    {
        public static Dispatcher UiDispatcher { get; private set; }

        /// 
        /// 检查操作是否是在UI线程上。假如操作在UI线程上则直接执行,否则调用UI Dispatcher线程执行。
        /// 
        /// 
        public static void CheckBeginInvokeOnUi(Action action)
        {
            if (action == null) return;
            CheckDispatcher();

            if (UiDispatcher.CheckAccess())
            {
                action();
            }
            else
            {
                UiDispatcher.BeginInvoke(action);
            }
        }

        private static void CheckDispatcher()
        {
            if (UiDispatcher == null)
            {
                var error = new StringBuilder("The DispatcherHelper is not initialized.");
                error.AppendLine();
                throw new InvalidOperationException(error.ToString());
            }
        }

        /// 
        /// 在UI线程上执行异步操作
        /// 
        /// 
        /// 
        public static DispatcherOperation RunAsync(Action action)
        {
            CheckDispatcher();

            return UiDispatcher.BeginInvoke(action);
        }

        /// 
        /// 在APP.Config的Application_Startup中初始化Initialize
        /// 
        public static void Initialize()
        {
            if (UiDispatcher != null && UiDispatcher.Thread.IsAlive)
            {
                return;
            }
            UiDispatcher = Dispatcher.CurrentDispatcher;
        }
    }

  

转载于:https://www.cnblogs.com/saybookcat/p/5190933.html

你可能感兴趣的:(ui)