UI线程中使用

public class SmartDispatcher

{

    public static void BeginInvoke(Action action)

    {

        if (Deployment.Current.Dispatcher.CheckAccess() 

            || DesignerProperties.IsInDesignTool)

        {

            action();

        }

        else

        {

            Deployment.Current.Dispatcher.BeginInvoke(action);

        }

    }

}

 
 
using System.ComponentModel;

 

namespace System.Windows.Threading

{

    /// <summary>

    /// A smart dispatcher system for routing actions to the user interface

    /// thread.

    /// </summary>

    public static class SmartDispatcher

    {

        /// <summary>

        /// A single Dispatcher instance to marshall actions to the user

        /// interface thread.

        /// </summary>

        private static Dispatcher _instance;

 

        /// <summary>

        /// Backing field for a value indicating whether this is a design-time

        /// environment.

        /// </summary>

        private static bool? _designer;

         

        /// <summary>

        /// Requires an instance and attempts to find a Dispatcher if one has

        /// not yet been set.

        /// </summary>

        private static void RequireInstance()

        {

            if (_designer == null)

            {

                _designer = DesignerProperties.IsInDesignTool;

            }

 

            // Design-time is more of a no-op, won't be able to resolve the

            // dispatcher if it isn't already set in these situations.

            if (_designer == true)

            {

                return;

            }

 

            // Attempt to use the RootVisual of the plugin to retrieve a

            // dispatcher instance. This call will only succeed if the current

            // thread is the UI thread.

            try

            {

                _instance = Application.Current.RootVisual.Dispatcher;

            }

            catch (Exception e)

            {

                throw new InvalidOperationException("The first time SmartDispatcher is used must be from a user interface thread. Consider having the application call Initialize, with or without an instance.", e);

            }

 

            if (_instance == null)

            {

                throw new InvalidOperationException("Unable to find a suitable Dispatcher instance.");

            }

        }

 

        /// <summary>

        /// Initializes the SmartDispatcher system, attempting to use the

        /// RootVisual of the plugin to retrieve a Dispatcher instance.

        /// </summary>

        public static void Initialize()

        {

            if (_instance == null)

            {

                RequireInstance();

            }

        }

 

        /// <summary>

        /// Initializes the SmartDispatcher system with the dispatcher

        /// instance.

        /// </summary>

        /// <param name="dispatcher">The dispatcher instance.</param>

        public static void Initialize(Dispatcher dispatcher)

        {

            if (dispatcher == null)

            {

                throw new ArgumentNullException("dispatcher");

            }

 

            _instance = dispatcher;

 

            if (_designer == null)

            {

                _designer = DesignerProperties.IsInDesignTool;

            }

        }

 

        /// <summary>

        /// 

        /// </summary>

        /// <returns></returns>

        public static bool CheckAccess()

        {

            if (_instance == null)

            {

                RequireInstance();

            }

 

            return _instance.CheckAccess();

        }

 

        /// <summary>

        /// Executes the specified delegate asynchronously on the user interface

        /// thread. If the current thread is the user interface thread, the

        /// dispatcher if not used and the operation happens immediately.

        /// </summary>

        /// <param name="a">A delegate to a method that takes no arguments and 

        /// does not return a value, which is either pushed onto the Dispatcher 

        /// event queue or immediately run, depending on the current thread.</param>

        public static void BeginInvoke(Action a)

        {

            if (_instance == null)

            {

                RequireInstance();

            }

 

            // If the current thread is the user interface thread, skip the

            // dispatcher and directly invoke the Action.

            if (_instance.CheckAccess() || _designer == true)

            {

                a();

            }

            else

            {

                _instance.BeginInvoke(a);

            }

        }

    }

}

SmartDispatcher 类的更多相关文章

  1. Java类的继承与多态特性-入门笔记

    相信对于继承和多态的概念性我就不在怎么解释啦!不管你是.Net还是Java面向对象编程都是比不缺少一堂课~~Net如此Java亦也有同样的思想成分包含其中. 继承,多态,封装是Java面向对象的3大特 ...

  2. C++ 可配置的类工厂

    项目中常用到工厂模式,工厂模式可以把创建对象的具体细节封装到Create函数中,减少重复代码,增强可读和可维护性.传统的工厂实现如下: class Widget { public: virtual i ...

  3. Android请求网络共通类——Hi_博客 Android App 开发笔记

    今天 ,来分享一下 ,一个博客App的开发过程,以前也没开发过这种类型App 的经验,求大神们轻点喷. 首先我们要创建一个Andriod 项目 因为要从网络请求数据所以我们先来一个请求网络的共通类. ...

  4. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库

    在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...

  5. ASP.NET Core 折腾笔记二:自己写个完整的Cache缓存类来支持.NET Core

    背景: 1:.NET Core 已经没System.Web,也木有了HttpRuntime.Cache,因此,该空间下Cache也木有了. 2:.NET Core 有新的Memory Cache提供, ...

  6. .NET Core中间件的注册和管道的构建(2)---- 用UseMiddleware扩展方法注册中间件类

    .NET Core中间件的注册和管道的构建(2)---- 用UseMiddleware扩展方法注册中间件类 0x00 为什么要引入扩展方法 有的中间件功能比较简单,有的则比较复杂,并且依赖其它组件.除 ...

  7. Java基础Map接口+Collections工具类

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  8. PHP-解析验证码类--学习笔记

    1.开始 在 网上看到使用PHP写的ValidateCode生成验证码码类,感觉不错,特拿来分析学习一下. 2.类图 3.验证码类部分代码 3.1  定义变量 //随机因子 private $char ...

  9. C# 多种方式发送邮件(附帮助类)

    因项目业务需要,需要做一个发送邮件功能,查了下资料,整了整,汇总如下,亲测可用- QQ邮箱发送邮件 #region 发送邮箱 try { MailMessage mail = new MailMess ...

随机推荐

  1. ArrayAccess(数组式访问)

    实现该接口后,可以像访问数组一样访问对象. 接口摘要: ArrayAccess { abstract public boolean offsetExists ( mixed $offset ) abs ...

  2. BigDecimal运算

    BigDecimal由任意精度整数未缩放值和32位整数级别组成 . 如果为零或正数,则刻度是小数点右侧的位数. 如果是负数,则数字的非标定值乘以10,以达到等级的否定的幂. 因此,BigDecimal ...

  3. SVN A C D M G U R I 的含义

    A:add,新增 C:conflict,冲突 D:delete,删除 M:modify,本地已经修改 G:modify and merGed,本地文件修改并且和服务器的进行合并 U:update,从服 ...

  4. Python面向对象,析构继承多态

    析构: def __del__(self): print("del..run...") r1 = Role("xx") del r1 结果打印del..run. ...

  5. Sturts2中Action的搜索顺序

    http://localhost:8080/ProjectName/path1/path2/path3/XX.action 首先会判断以/path1/paht2/path3为namespace的pac ...

  6. swing之单选框和复选框

    import java.awt.Container; import java.awt.GridLayout; import javax.swing.*; public class num_1v ext ...

  7. Divide Groups 二分图的判定

    Divide Groups Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Tot ...

  8. Leetcode 22.生成括号对数

    生成括号对数 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n =3,生成结果为: [ "((()))", "( ...

  9. COJ 1411 Longest Consecutive Ones

    题目大意: 希望在 k 步之内,将尽可能多的1移到相邻的位置上 这里依靠前缀和解决问题 我们用pos[i]保存第i个1的位置,这里位置我以1开始 用sum[i]保存前 i 个1从 0 点移到当前位置所 ...

  10. Codeforces Round #254 (Div. 1) C DZY Loves Colors

    http://codeforces.com/contest/444/problem/C 题意:给出一个数组,初始时每个值从1--n分别是1--n.  然后两种操作. 1:操作 a.b内的数字是a,b内 ...