A Brief Introduction to cross-thread access control in. Net3.0,. net3.0
During the past two days, when using WPF as the UI part of a project, it was found that the UI control was accessed across threads, and an exception was reported naturally. At that time, I did not find the InvokeRequired attribute and the Invoke method in the control for a long time. I was very depressed and found that in. net3.0, this changed.
The method used to replace InvokeRequired is the DispatcherObject. CheckAccess () or DispatcherObject. VerifyAccess () method, which indicates whether the current thread can directly access the control.
The method to replace Invoke is the DispatcherObject. Dispatcher. BeginInvoke (...) method.
Reference code:
// 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 );
}
}
} Reprinted from: http://www.aspnetjia.com/Cont-172.html