How to check calling thread is associated with current dispatcher


In WPF dispatcher has method CheckAccess method which is used to check whether calling thread is associated with current dispatcher. This method is equivalent to control.InvokeRequired property. There is another method VerifyAccess which does same thing as CheckAccess only difference that CheckAccess returns boolean value on other hand VerifyAccess throws exception.

Example of CheckAccess

public void SetTitle(string text)
{
    if (this.Dispatcher.CheckAccess())
    {
        //Set text here on some control
    }
    else
    {
        // This thread does not have access to the UI thread. 
        // Place the update method on the Dispatcher of the UI thread.
        Action act = delegate()
        {
            SetTitle(text);
        };
        this.Dispatcher.BeginInvoke(act, null);
    }
}

In above example if SetTitle will be called from some other thread then return value of CheckAccess will be false and it will invoked for current thread dispatcher.

In WPF, you can call Dispatcher.Invoke regardless of your current thread, and it\’ll handle the call accordingly – if you\’re already on the right thread, it\’ll just invoke your code, and it uses CheckAccessto handle this behaviour.

just call Dispatcher.Invoke and don\’t worry about CheckAccess.

Why this method is not visible in VS intelisense?

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

It is hidden via [EditorBrowsable(EditorBrowsableState.Never)] attribute.