這兩天用WPF做一個項目的UI部分時, 發現跨線程地訪問了UI控件, 自然地報異常了. 當時找了半天也沒在控件中找到InvokeRequired屬性和Invoke方法, 郁悶之極.....最後發現在.net3.0中,這有所改變了.
替代InvokeRequired的方法是DispatcherObject.CheckAccess()或DispatcherObject.VerifyAccess()方法,用於指示當前線程是否可以直接訪問控件.
替代Invoke的方法是DispatcherObject.Dispatcher.BeginInvoke(...)方法
參考代碼:
// Uses the DispatcherObject.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.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
// Pushing update method on the Dispatcher of the UI thread
theButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new UpdateUIDelegate(UpdateButtonUI), theButton);
}
}
}