這兩天用WPF做一個(gè)項(xiàng)目的UI部分時(shí),發(fā)現(xiàn)跨線程地訪問了UI控件,自然地報(bào)異常了。當(dāng)時(shí)找了半天也沒在控件中找到InvokeRequired屬性和Invoke方法,郁悶之極.....最后發(fā)現(xiàn)在.net3.0中,這有所改變了。
// 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);
}
}
}