DependencyObject.CheckAccess Method

May 11, 2014

Determines whether the calling thread has access to this object.

Namespace:  System.Windows
Assembly:  System.Windows (in System.Windows.dll)

public bool CheckAccess()

Return Value

Type: System.Boolean
true if the calling thread has access to this object; otherwise, false.

CheckAccess is a utility method that determines whether a threading context that has obtained a DependencyObject is the same thread that the DependencyObject was created on.

  • If it is the same thread, CheckAccess returns true. You can perform actions on that DependencyObject. This might include setting properties, calling methods and so on.

  • If the current threading context is not the creating thread, CheckAccess returns false. Nearly all attempts to perform actions that attempt to change values on the DependencyObject will raise exceptions in this circumstance. However, you can retrieve the Dispatcher value from that DependencyObject, and use the Dispatcher API to invoke the action. For more information, see Dispatcher.

Any thread can check to see if it has access to a particular DependencyObject.

If CheckAccess returns false, this typically means that you are attempting to access a DependencyObject on the main UI thread, from a threading context that is not the main UI thread.

BackgroundWorker is a possible option for delegating threads to perform actions that are not using the main UI thread.

The following code example demonstrates how to use this method to check whether an action can be performed against a DependencyObject on the UI thread, and uses BeginInvoke in cases where CheckAccess returns false.


private delegate void AddTextDelegate(Panel p, String text);

private void AddText(Panel p, String text)
{
    p.Children.Clear();
    p.Children.Add(new TextBlock { Text = text });
}

private void TestBeginInvokeWithParameters(Panel p)
{
    if (p.Dispatcher.CheckAccess()) AddText(p, "Added directly.");
    else p.Dispatcher.BeginInvoke(
        new AddTextDelegate(AddText), p, "Added by Dispatcher.");
}


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2014 Microsoft