DispatcherHelper

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

        /// <summary>
        /// 检查操作是否是在UI线程上。假如操作在UI线程上则直接执行,否则调用UI Dispatcher线程执行。
        /// </summary>
        /// <param name="action"></param>
        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());
            }
        }

        /// <summary>
        /// 在UI线程上执行异步操作
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public static DispatcherOperation RunAsync(Action action)
        {
            CheckDispatcher();

            return UiDispatcher.BeginInvoke(action);
        }

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

  

你可能感兴趣的:(DispatcherHelper)