Threads, UI, and Invoke (again)...

I know this has been asked at least a few times before, but i am having horrible trouble trying to get this to work.

Maybe i need it explained to me like a 5 year old... because i am new to C#.

What I am trying to do, is, of course, update the UI of one form from another thread...
In more detail, i mean, I am trying to simply appendtext to a richtextbox from one form
from a thread on another .cs file that streams a simple TCP connection... i just want to post
all messages from it to the richtextbox.

I dont have code to paste since i deleted it all to start over.

I need to append this variable of the connections message, to the end of a richtext. Everytime i've tried, it will compile fine, no errors, but will not update. Ive tried invoke, begininvoke, ive written delegates for it, but im more then confused at this point.

Could someone have the heart to explain it as simply as possible, with maybe somewhat detailed example

It's driving me crazy!



Answer this question

Threads, UI, and Invoke (again)...

  • Jombi

    Here is a small example. I created a new winforms application and added a progressbar and a button. I then start a new thread and updates the progressbar from the thread.

    The important part is the Invoke() method. This lets you execute code in the controls thread.

    EDIT: I see you probably already got it answered. In another thread you started. Maybe somebody else can learn for this code example.

    Thread t;
    private void button1_Click(object sender, EventArgs
    e)
    {
       progressBar1.Value = 0;
       progressBar1.Minimum = 0;
       progressBar1.Maximum = 100;
       t =
    new Thread(new ThreadStart
    (CountAndExitThread));
       t.Start();
    }

    private void CountAndExitThread()
    {
       for (int
    i = 1; i <= 100; i++)
       {
          progressBar1.Invoke(
    new ProgressBarIncrementDelegate
    (ProgressBarIncrement));
          Thread
    .Sleep(50);
       }
    }

    private delegate void ProgressBarIncrementDelegate();
    private void
    ProgressBarIncrement()
    {
       progressBar1.Value++;
    }



  • Threads, UI, and Invoke (again)...