Why are DispatcherObject.CheckAccess() and VerifyA

2020-03-08 12:34发布

问题:

The System.Windows.Threading.DispatcherObject class (which DependencyObject is based on) contains a useful function, called CheckAccess(), that determines whether or not the code is running on the UI thread.

When I wanted to use it yesterday, I was puzzled to find out that Intellisense didn't show the function (nor VerifyAccess(), which throws an exception when not on the UI thread), even though the MSDN library lists it. I decided to investigate the class using Reflector. It seems that the function in question has an EditorBrowsable(EditorBrowsableState.Never) attribute attached to it. The Dispatcher class, which is used by DispatcherObject, has the same attribute attached to CheckAccess() and VerifyAccess():

public abstract class DispatcherObject
{
    // ...

    [EditorBrowsable(EditorBrowsableState.Never)]
    public bool CheckAccess();
    [EditorBrowsable(EditorBrowsableState.Never)]
    public void VerifyAccess();

    // ...

    [EditorBrowsable(EditorBrowsableState.Advanced)]
    public Dispatcher Dispatcher { get; }
}


public sealed class Dispatcher
{
    // ...

    [EditorBrowsable(EditorBrowsableState.Never)]
    public bool CheckAccess();
    [EditorBrowsable(EditorBrowsableState.Never)]
    public void VerifyAccess();

    // ...
}

I don't believe that the application of that attribute is random (or a joke), so my question is: why is it there? Should those methods not be called directly? Then why aren't they protected (or internal, like some of the most useful methods in the WPF)?

回答1:

A Microsoft employee recently stated CheckAccess is used only for "advanced scenarios", so they hid it from Intellisense.

"CheckAccess and VerifyAccess have always been marked to be not visible, maybe IntelliSense wasn't respecting it. You can use Reflector to confirm. The idea here is that CheckAccess and VerifyAccess are advances scenarios, that normal developers don't need.

However, I do think that EditorBrowsableState.Advanced would have been a more appropriate level."

There's a Microsoft Connect case for this shortcoming. Vote for it if it's important to you.



回答2:

I can't find any documentation that says you shouldn't use those methods directly, but I haven't looked very long.

Also you refer to the EditorVisibleAttribute, which doesn't exist. According to Reflector it's the EditorBrowsableAttribute.

Reflector disassembly:

[EditorBrowsable(EditorBrowsableState.Never)]
public bool CheckAccess()
{
//CODE
}