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) {}
}