I am working on the following program which deals with threads and thread priorities.
I have constructed a windows form containing a rich textbox (DisplayTextBox) and two buttons (StartButton for running app and ExitButton for closing app).
In the form, I am creating several threads and running them one after another. The method used by each thread is found in the Threading class. The method in question is PrintOnScreen().
In this method, I am appending the thread name as well as its priority to str of type StringBuilder. Then I want to display the contents of str in DisplayTextBox (which is in Form.cs).
However, I am getting a “NullReferenceException was unhandled: Object reference not set to an instance of an object” error. The line where the error crops up is the following:
DisplayTextBox.Text = Convert.ToString(str);
Can you please help me to solve this error? Thanks.
Edit
Thanks to all for your help. In order to solve the problem, I copied the PrintOnScreen method to the Form.cs class and discarded Threading.cs.
I later used the code given by Anand and placed it below t2.Join(). Now it works like a charm.
The problem occurs in the constructor of your form. You declare
DisplayTextagain as local member, so that the field of your form isn’t initialized. Change your constructor like this:and it should work like you expect.
Edit: But beware of the problems you will get, when you want to change UI elements from a background worker thread. In those cases you will have to use the invoke pattern.