共用方式為


Dispatcher.VerifyAccess 方法

定義

判斷呼叫的執行是否可以存取這個 Dispatcher

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

例外狀況

呼叫執行緒無法存取這個 Dispatcher

範例

下列範例會使用 VerifyAccess 來判斷線程是否能夠存取所建立的執行緒 Button 。 方法會採用 物件做為引數,而這個引數會 Button 轉換成 。 VerifyAccess上的 Dispatcher Button 方法會呼叫 來驗證執行緒的存取權。

如果呼叫執行緒具有 的存取 Dispatcher 權,則 Button 只會存取 的成員 Button 來更新 。

如果呼叫執行緒沒有存取權, InvalidOperationException 則會擲回 。 這個範例會攔截例外狀況,並將接受 Button 做為引數的 委派推送至 DispatcherButton 。 這會 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 存取權。

如果呼叫執行緒沒有 存取 Dispatcher 權,且 VerifyAccess 擲回例外狀況,則 和 CheckAccess VerifyAccess 之間的差異 CheckAccess 會傳回布林值。

適用於

另請參閱