If the sub-thread needs to directly access the control under the main thread, an error will be reported when running in debug mode. The prompt is roughly as follows:
The Inter-thread operation is invalid: It is accessed by a thread that does not create the control "XXXX.
Solution: Delegate (proxy) The solution:
Assume that the sub-thread wants to bind data to the listview1 control:
Step 1:
Public Delegate void safebind (listviewitem LVI); // delegate a cross-thread access control
Safebind;
Step 2:
Public void bindlistview (String title, string content)
{
Listviewitem LVI = new listviewitem (datetime. Now. tostring ());
LVI. subitems. addrange (New String [] {Title, content });
Safeinsetitem (LVI); // executes the Security binding method.
}
Step 3:
Private void safeinsetitem (listviewitem LVI)
{
If (this. listview1.invokerequired) // returns true, indicating that the call thread is different from the control creation thread.
{
Safebind = new safebind (safeinsetitem );
This. Invoke (safebind, LVI); // execute the delegate with Parameters
}
Else
{
This. listview1.items. Add (LVI );
}
}
The essence of the above Code is that the subthread calls the delegate under the main thread, and the delegate executes the binding method.
Why is an error reported without entrusting? -- Microsoft's Secure Access Mechanism (it is insecure for multiple threads to access the same component)
Reference URL: http://zhidao.baidu.com/question/14949954.html? An = 0 & Si = 5
Http://zhidao.baidu.com/question/112998876.html? An = 0 & Si = 8
Http://zhidao.baidu.com/question/70832540.html