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

阅读: 评论:0

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

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

在 WPF 程序中,可能会存在 Application.Current.Dispatcher.Xxx 这样的代码让一部分逻辑回到主 UI 线程。因为发现在调用这句代码的时候出现了 NullReferenceException,于是就有三位小伙伴告诉我说 CurrentDispatcher 属性都可能为 null

然而实际上这里只可能 Currentnull 而此上下文的 Dispatcher 是绝对不会为 null 的。(当然我们这里讨论的是常规编程手段,如果非常规手段,你甚至可以让实例的 thisnull 呢……)


由于本文所述的两个部分都略长,所以拆分成两篇博客,这样更容易理解。

  • WPF 的 Application.Current.Dispatcher 中,Dispatcher 属性一定不会为 null
  • WPF 的 Application.Current.Dispatcher 中,为什么 Current 可能为 null

本文内容

    • `Application.Dispatcher` 实例属性
      • 源代码
      • 赋值时机
      • 后续赋值
      • 结论
    • `Application.Current` 静态属性

Application.Dispatcher 实例属性

Application.Dispatcher 实例属性来自于 DispatcherObject

源代码

为了分析此属性是否可能为 null,我现在将 DispatcherObject 的全部代码贴在下面:

using System;
using System.Windows;
using System.Threading;
using MS.Internal.WindowsBase;               // FriendAccessAllowednamespace System.Windows.Threading
{/// <summary>///     A DispatcherObject is an object associated with a///     <see cref="Dispatcher"/>.  A DispatcherObject instance should///     only be access by the dispatcher's thread./// </summary>/// <remarks>///     Subclasses of <see cref="DispatcherObject"/> should enforce thread///     safety by calling <see cref="VerifyAccess"/> on all their public///     methods to ensure the calling thread is the appropriate thread.///     <para/>///     DispatcherObject cannot be independently instantiated; that is,///     all constructors are protected./// </remarks>public abstract class DispatcherObject{/// <summary>///     Returns the <see cref="Dispatcher"/> that this///     <see cref="DispatcherObject"/> is associated with./// </summary>[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]public Dispatcher Dispatcher{get{// This property urn _dispatcher;}}// This method allows certain derived classes to break the dispatcher affinity// of our objects.[FriendAccessAllowed

本文发布于:2024-02-02 02:53:51,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170681564840931.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:会为   属性   Current   WPF   Application
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23