码迷,mamicode.com
首页 > 其他好文 > 详细

DispatcherHelper

时间:2016-02-15 18:12:24      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

 /// <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

标签:

原文地址:http://www.cnblogs.com/saybookcat/p/5190933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!