DependencyObject.CheckAccess Method

July 28, 2014

Determines whether the calling thread has access to this object.

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

'Declaration
Public Function CheckAccess As Boolean

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 Sub AddTextDelegate(ByVal p As Panel, ByVal text As String)

Private Sub AddText(ByVal p As Panel, ByVal text As String)
    p.Children.Clear()
    Dim t As New TextBlock
    t.Text = text
    p.Children.Add(t)
End Sub

Private Sub TestBeginInvokeWithParameters(ByVal p As Panel)
    If p.Dispatcher.CheckAccess() _
        Then AddText(p, "Added directly.") _
        Else p.Dispatcher.BeginInvoke(New AddTextDelegate( _
            AddressOf AddText), p, "Added by Dispatcher.")
End Sub


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2014 Microsoft