Thomas

Thomas

  • NA
  • 7
  • 0

Multithreading poblem (beginners question)

Nov 27 2009 2:44 AM
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

Answers (3)