Dispatcher.CheckAccess 方法

定义

确定调用线程是否是与此 Dispatcher关联的线程。

public:
 bool CheckAccess();
public bool CheckAccess();
member this.CheckAccess : unit -> bool
Public Function CheckAccess () As Boolean

返回

true 如果调用线程是与此 Dispatcher关联的线程,则为 ;否则为 false

示例

以下示例用于CheckAccess确定线程是否有权访问 。Button 调用与 /> 关联的方法以验证对线程的访问。 如果调用线程有权访问该 Dispatcher调用线程, Button 则通过访问成员 Button来更新;否则,接受作为参数的委托将被放置在该委托 ButtonDispatcher。 将 Dispatcher 委托更新该 Button操作的工作。

// Uses the Dispatcher.CheckAccess method to determine if
// the calling thread has access to the thread the UI object is on.
private void TryToUpdateButtonCheckAccess(object uiObject)
{
    Button theButton = uiObject as Button;

    if (theButton != null)
    {
        // Checking if this thread has access to the object.
        if (theButton.Dispatcher.CheckAccess())
        {
            // This thread has access so it can update the UI thread.
            UpdateButtonUI(theButton);
        }
        else
        {
            // This thread does not have access to the UI thread.
            // Place the update method on the Dispatcher of the UI thread.
            theButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new UpdateUIDelegate(UpdateButtonUI), theButton);
        }
    }
}
' Uses the Dispatcher.CheckAccess method to determine if 
' the calling thread has access to the thread the UI object is on.
Private Sub TryToUpdateButtonCheckAccess(ByVal uiObject As Object)
    Dim theButton As Button = TryCast(uiObject, Button)

    If theButton IsNot Nothing Then
        ' Checking if this thread has access to the object.
        If theButton.Dispatcher.CheckAccess() Then
            ' This thread has access so it can update the UI thread.
            UpdateButtonUI(theButton)
        Else
            ' This thread does not have access to the UI thread.
            ' Place the update method on the Dispatcher of the UI thread.
            theButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal, New UpdateUIDelegate(AddressOf UpdateButtonUI), theButton)
        End If
    End If
End Sub

注解

Dispatcher只有创建对象DispatcherObject才能访问对象。 使用 InvokeBeginInvoke 从其他线程访问对象。

CheckAccess 可以从任何线程调用。

这两者之间的差异CheckAccessVerifyAccessCheckAccess返回一个布尔值,指示调用线程是否有权访问DispatcherVerifyAccess引发异常。

适用于

另请参阅