Hi
I'm new to C# and have tried to fiddle with a some simple multithreading. I wanted to make a thread that prompts some text in a textbox every second but the thread only prompts text once and then does no more.
In the code below you can see what I have done.
private void ThreadText()
{
string text = "Written by the background thread. ";
if (this.textBox1.InvokeRequired)
{
// It's on a different thread, so use Invoke.
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke
(d, new object[] { text + " (Invoke) " + tmp++ });
}
else
{
// It's on the same thread, no need for Invoke
this.textBox1.Text = text + " (No Invoke)" + tmp++ + "\n";
}
Thread.Sleep(1000);
}
In my main I instantiate the thread like this:
{
myThread = new Thread(new ThreadStart(this.ThreadText));
myThread.Start();
}
Can someone please tell me what is wrong with my code?
Best Regards
Thomas
Loading
Nilanka DharmadasaPosted Nov 27, 2009, 3:32 AM
Your code should come insdie a while loop. See my code.
Please do not forget to mark Do you like this answer checkbox if you like my answer.
private void ThreadText()
{
string text = "Written by the background thread. ";
while(true)
Nilanka DharmadasaPosted Nov 27, 2009, 11:39 AM
Yes. It's totally ok to ask your questions. :) We are here to answer them.
The reason for using a while loop is to continue your expected work. Otherwise, once one cycle is done, the thread finishes its work and quits.
But now the thread will work until we exit the application. So when you want to exit the application, first you should stop the thread.
In your form closing event you can stop the thread.
Hope my answer helps. :)
ThomasPosted Nov 27, 2009, 9:32 AM
Thanks a lot - this tip worked fine. Although I wonder why you have to do the while-loop thing?
Also when I quit my program I get a "objectDisposedException was unhandled" error. Since I can't find a destructor method I wonder how I ensure that the thread is stopped upon quiting?
Hope that it is ok that I ask this also!
Best Regards
Thomas