C # Solve multithreading frequently manipulate the same control appears "not setting an object reference to an instance of an object"

Source: Internet
Author: User

In C # Software design, if there are multiple threads that frequently manipulate the same control of the UI main thread at the same time, such as display status, the error of "not setting an object reference to an instance of an object" is often encountered.

Sometimes even if you use Try...catch ... To catch bugs is still useless, such as a recent small development application. 5 threads need to write the state to the RichTextBox control frequently, while 5 threads are writing data at the same time, but after running for a while, there will be an "object reference not set to an instance of object" error, or the software automatically exits.

Such an unusual customer must be dissatisfied. I guess the problem still appears in multithreading, even if you add the following sentence:

Control.checkforillegalcrossthreadcalls = false;

In order to allow unsafe calls from threads, errors can still occur within. NET.

The workaround is to use the String StringBuilder class (string, but not as efficient StringBuilder), temporarily cache the data to be displayed, and then use a timer to write to the RichTextBox control at timed intervals. This avoids the frequent manipulation of the same control.

StringBuilder TMPV = new StringBuilder ();
TMPV. Appendline ("...");

The timer interval can be set to 5 seconds, and every 5 seconds the data in the TMPV is displayed to the RichTextBox.

private void Timer1_Tick (object sender, EventArgs e)
{//Timer
Try
{
Richtextbox1.appendtext (TMPV. ToString ());
TMPV. Length = 0; Empty StringBuilder
}
catch (Exception) {}
}

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.