Dispatcher.VerifyAccess 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
判斷呼叫執行緒是否能存取此 Dispatcher。
public:
void VerifyAccess();
public void VerifyAccess();
member this.VerifyAccess : unit -> unit
Public Sub VerifyAccess ()
例外狀況
呼叫執行緒無法存取此 Dispatcher。
範例
以下範例用 VerifyAccess 來判斷執行緒是否能存取 a Button 所建立的執行緒。 此方法取一個物件作為參數,並將其鑄造成 Button。 VerifyAccess呼叫 的 DispatcherButton 方法來驗證對執行緒的存取。
如果呼叫執行緒能存取 Dispatcher,則 Button 只需存取 的成員 Button即可更新。
若呼叫執行緒無法存取,則拋出 an InvalidOperationException 執行緒。 此範例捕捉例外,並將接受 a 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(),
"Exception 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。
若呼叫執行緒無法存取 ,CheckAccess則 與 之間的差異VerifyAccessCheckAccessDispatcher會回傳布林值,並VerifyAccess拋出例外。