这两天用WPF做一个项目的UI部分时,发现跨线程地访问了UI控件,自然地报异常了。当时找了半天也没在控件中找到InvokeRequired属性和Invoke方法,郁闷之极.....最后发现在.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);
}
}
}