How does one report an error when the sub-thread accesses the control under the main thread?

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.