在 WPF 程序中,可能会存在 Application.Current.Dispatcher.Xxx
这样的代码让一部分逻辑回到主 UI 线程。因为发现在调用这句代码的时候出现了 NullReferenceException
,于是就有三位小伙伴告诉我说 Current
和 Dispatcher
属性都可能为 null
。
然而实际上这里只可能 Current
为 null
而此上下文的 Dispatcher
是绝对不会为 null
的。(当然我们这里讨论的是常规编程手段,如果非常规手段,你甚至可以让实例的 this
为 null
呢……)
由于本文所述的两个部分都略长,所以拆分成两篇博客,这样更容易理解。
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小时内删除。
留言与评论(共有 0 条评论) |