Dispatcher.VerifyAccess 方法

定义

确定调用线程是否可以访问此 Dispatcher

public:
 void VerifyAccess();
public void VerifyAccess ();
member this.VerifyAccess : unit -> unit
Public Sub VerifyAccess ()

例外

调用线程不能访问此 Dispatcher

示例

以下示例用于 VerifyAccess 确定线程是否有权访问创建线程的线程 Button 。 该方法采用对象作为参数,该参数被强制转换为 .Button 调用VerifyAccess该方法DispatcherButton以验证对线程的访问。

如果调用线程有权访问该 Dispatcher调用线程, Button 则只需访问成员 Button即可更新该线程。

如果调用线程没有访问权限,则会引发一个 InvalidOperationException 。 此示例捕获异常,并将接受 Button 作为参数的委托推送到 Dispatcher 其中 Button。 此操作 Dispatcher 将执行更新操作 Button

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

    if (theButton != null)
    {
        try
        {   
            // Check if this thread has access to this object.
            theButton.Dispatcher.VerifyAccess();

            // The thread has access to the object, so update the UI.
            UpdateButtonUI(theButton);
        }

        // Cannot access objects on the thread.
        catch (InvalidOperationException e)
        {
            // Exception Error Message.
            MessageBox.Show("Exception ToString: \n\n" + e.ToString(), 
                "Execption Caught! Thrown During AccessVerify().");

            MessageBox.Show("Pushing job onto UI Thread Dispatcher");

            // Placing job onto the Dispatcher of the UI Thread.
            theButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new UpdateUIDelegate(UpdateButtonUI), theButton);
        }
    }
}
' Uses the Dispatcher.VerifyAccess method to determine if 
' the calling thread has access to the thread the UI object is on.
Private Sub TryToUpdateButtonVerifyAccess(ByVal uiObject As Object)
    Dim theButton As Button = TryCast(uiObject, Button)

    If theButton IsNot Nothing Then
        Try
            ' Check if this thread has access to this object.
            theButton.Dispatcher.VerifyAccess()

            ' The thread has access to the object, so update the UI.
            UpdateButtonUI(theButton)

            ' Cannot access objects on the thread.
        Catch e As InvalidOperationException
            ' Exception Error Message.
            MessageBox.Show("Exception ToString: " & vbLf & vbLf & e.ToString(), "Execption Caught! Thrown During AccessVerify().")

            MessageBox.Show("Pushing job onto UI Thread Dispatcher")

            ' Placing job onto the Dispatcher of the UI Thread.
            theButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal, New UpdateUIDelegate(AddressOf UpdateButtonUI), theButton)
        End Try
    End If
End Sub

注解

只有创建时Dispatcher创建的线程可以访问 。Dispatcher

此方法是公共的;因此,任何线程都可以检查它是否有权访问 Dispatcher

如果调用线程无权访问DispatcherVerifyAccess引发异常,则两者之间的差异CheckAccess CheckAccess VerifyAccess返回布尔值。

适用于

另请参阅