DispatcherObject,Dispatcher,Thread之间的关系
我们都知道WPF中的控件类都是从System.Windows.Threading.DispatcherObject继承而来, 而DispatcherObject又在构造时与当前线程的Dispatcher关联起来,CurrentDispatcher如果为null则会主动new一个Dispatcher并且在构造时和当前创建它的线程关联起来了。因此整个链为DispatcherObject <- Dispatcher <- Thread. 具体我们一起看看反编译的红色代码:
public abstract class DispatcherObject
{
    private Dispatcher _dispatcher;
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    public Dispatcher Dispatcher
    {
      get
      {
        return this ._dispatcher;
      }
    }
    protected DispatcherObject()
    {
      base .\u002Ector();
      this ._dispatcher = Dispatcher.CurrentDispatcher;
    }
     ........................................................
}
public sealed class Dispatcher
{
      public static Dispatcher CurrentDispatcher
     {
      get
      {
        return Dispatcher.FromThread(Thread.CurrentThread) ?? new Dispatcher();
      }
     }
    private Dispatcher()
    {
     .............................
      Dispatcher._tlsDispatcher = this ;
      this ._dispatcherThread = Thread.CurrentThread;
     .............................
    }
     ..............................
}
这样设计的原则就保证:界面元素只有被创建它的线程访问
Dispatcher中Invoke,BeginInvoke和Win32中SendMessage,PostMessage的关系
上面我们提到wpf的界面元素只有被创建它的线程来访问,如果我们想在后台或者其他线程里该怎么办?
答案就是利用Dispatcher的Invoke和BeginInvoke,作用就是把委托放到界面元素关联的Dispatcher里的工作项里,然后此Dispatcher关联的线程进行执行。
所不同的是Invoke是在关联的线程里同步执行委托, 而BeginInvoke是在关联的线程里异步执行委托。
做过Win32或者MFC编程的童鞋们都知道win32中有SendMessage和PostMessage类似的概念,这些概念有什么内在关系呢?
其实Dispatcher的Invoke和BeginInvoke都是调用Win32的PostMessage传递窗体句柄和消息号,反编译代码如下:
    private bool RequestForegroundProcessing()
    {
      if (this._postedProcessingType >= 2)
        return true;
      if (this._postedProcessingType == 1)
        SafeNativeMethods.KillTimer(new HandleRef((object) this, this._window.Value.Handle), 1);
      this._postedProcessingType = 2;
      return MS.Win32.UnsafeNativeMethods.TryPostMessage(new HandleRef((object) this, this._window.Value.Handle), Dispatcher._msgProcessQueue, IntPtr.Zero, IntPtr.Zero);
    }
只不过Invoke在PostMessage后调用了内部返回值DispatcherOperation的wait方法,在执行结束后才返回。反编译代码如下:
      DispatcherOperation dispatcherOperation = this.BeginInvokeImpl(priority, method, args, isSingleParameter);
        if (dispatcherOperation != null)
        {
          int num = (int) dispatcherOperation.Wait(timeout);
          if (dispatcherOperation.Status == DispatcherOperationStatus.Completed)
            obj = dispatcherOperation.Result;
          else if (dispatcherOperation.Status == DispatcherOperationStatus.Aborted)
            obj = (object) null;
          else
            dispatcherOperation.Abort();
        }
WPF的消息泵和Win32的消息泵之间的关系
WPF的窗体程序都必须隐式或者显式调用Application.Run()来初始化WPF窗体。当Application.Run()调用时, 会在其内部调用Dispatcher.Run()方法。最终会在PushFrame()方法内初始化消息泵。
具体为:Application.Run() -> Dispatcher.Run() -> Dispatcher.PushFrame() -> Dispatcher.PushFrameImpl()
private void PushFrameImpl(DispatcherFrame frame)
    {
      MSG msg = new MSG();
      ++this._frameDepth;
      try
      {
        SynchronizationContext current = SynchronizationContext.Current;
        bool flag = current != this._dispatcherSynchronizationContext;
        try
        {
          if (flag)
            SynchronizationContext.SetSynchronizationContext((SynchronizationContext) this._dispatcherSynchronizationContext);
          while (frame.Continue && this.GetMessage(ref msg, IntPtr.Zero, 0, 0))
            this.TranslateAndDispatchMessage(ref msg);
          if (this._frameDepth != 1 || !this._hasShutdownStarted)
            return;
          this.ShutdownImpl();
        }
        finally
        {
          if (flag)
            SynchronizationContext.SetSynchronizationContext(current);
        }
      }
      finally
      {
        --this._frameDepth;
        if (this._frameDepth == 0)
          this._exitAllFrames = false;
      }
    }
Ok,从上述反编译的代码可以看到,WPF还是通过Dispatcher内部实现了传统的Win32消息循环, 如GetMessage,TranslateMessage,DispatchMessage。
下面是win32消息泵的实现, 大家可以对比下:
BOOL bRet;

while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0)
{
    if (bRet == -1)
    {
        // handle the error and possibly exit
    }
    else
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

聊聊WPF中的Dispatcher的更多相关文章

  1. 聊聊WPF中字体的设置

    1. 今天帮同事调试一个字体的bug:TextBox中的中文显示大小不一致, 比如包含"杰","热". 原因是WPF针对点阵字体需要指定特定字体才能正确渲染, ...

  2. WPF:浅析Dispatcher

    本人文笔差.还是直接上代码吧.(本文假设你对WPF中的Dispatcher有一定的了解) 你觉得下面的代码可以正常执行吗? private void Button_Click(object sende ...

  3. WPF 中那些可跨线程访问的 DispatcherObject(WPF Free Threaded Dispatcher Object)

    原文 WPF 中那些可跨线程访问的 DispatcherObject(WPF Free Threaded Dispatcher Object) 众所周知的,WPF 中多数对象都继承自 Dispatch ...

  4. WPF 的 Application.Current.Dispatcher 中,Dispatcher 属性一定不会为 null

    原文:WPF 的 Application.Current.Dispatcher 中,Dispatcher 属性一定不会为 null 在 WPF 程序中,可能会存在 Application.Curren ...

  5. MVVM模式解析和在WPF中的实现(六) 用依赖注入的方式配置ViewModel并注册消息

    MVVM模式解析和在WPF中的实现(六) 用依赖注入的方式配置ViewModel并注册消息 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二 ...

  6. MVVM模式解析和在WPF中的实现(五)View和ViewModel的通信

    MVVM模式解析和在WPF中的实现(五) View和ViewModel的通信 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 M ...

  7. 【WPF】 Timer与 dispatcherTimer 在wpf中你应该用哪个?

    源:Roboby 1.timer或重复生成timer事件,dispatchertimer是集成到队列中的一个时钟.2.dispatchertimer更适合在wpf中访问UI线程上的元素 3.Dispa ...

  8. WPF线程(Step1)——Dispatcher

    使用WPF开发时经常会遇上自己建立的线程需要更新界面UI内容,从而导致的跨线程问题. 异常内容: 异常类型:System.InvalidOperationException 异常描述: "S ...

  9. WPF中Timer与DispatcherTimer类的区别

    前几天在WPF中写了一个轨迹回放的功能,我想稍微做过类似项目的,都晓得采用一个时间控件或者时间对象作为调度器,我在这么做的时候,出现了问题,于是将程序中的Timer换成了DispatchTimer,然 ...

随机推荐

  1. R语言的输出函数cat,sink,writeLines,write.table

    根据输出的方向分为输出到屏幕和输出到文件. 1.cat函数即能输出到屏幕,也能输出到文件. 使用方式:cat(... , file = "", sep = " " ...

  2. bowtie2用法

    bowtie2的功能:短序列的比对 用法:bowtie2 [options]* -x <bt2-idx> {-1 <m1> -2 <m2> | -U <r&g ...

  3. linux 无密码登录

    环境:Linux 脚本:Python 功能:批量IP,远程执行命令.拷贝文件 运行:./ssh_scp.py iplist.txt 脚本内容: #!/usr/bin/env python# -*- c ...

  4. C#多线程学习之Thread

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  5. INSPIRED启示录 读书笔记 - 第31章 苹果公司给我的启示

    苹果公司值得学习的经验 1.硬件为软件服务:苹果公司明白硬件必须为软件服务,软件直接服务用户,满足用户需求.采用多点触控显示屏.重力加速器.距离传感器这些硬件技术是为了配合软件满足用户需求 2.软件为 ...

  6. JMeter学习(一)目录介绍

    JMeter也学了一阵子了,对于基本的操作已了解,再回过头来看看Jmeter的目录,本篇是对于它的目录进行一些简单的介绍. JMeter解压之后打开,根目录如下图: 1.bin:可执行文件目录 2.d ...

  7. JSP--内置对象&动作标签介绍

    1.JSP中常用的9大内置对象? 内置对象:在JSP页面中能直接使用的对象就是JSP内置对象,事实上,JSP底层就是一个java类,可以在JSP中直接使用的,必然存在JSP翻译后的java类 下面简单 ...

  8. gzip: stdin: unexpected end of file tar: Unexpected EOF in archive

    1.问题描述: 今天解压tar包遇到这样一个问题 使用命令:tar -zxvf  xxxxx.tar.gz gzip: stdin: unexpected end of filetar: Unexpe ...

  9. tp3.2关联模型 BELONGS_TO

    <?php namespace Home\Model; use Think\Model\RelationModel; class AttenModel extends RelationModel ...

  10. Live disk migration with libvirt blockcopy

    nova采用 libvirt blockcopy(python  API virDomainBlockRebase)来做live snapshot. Create the base image: $ ...