C# Threading using invoke, freezing the form C# Threading using invoke, freezing the form multithreading multithreading

C# Threading using invoke, freezing the form


This solution works ! Have checked it.

The problem is you keep telling the UI thread to change the Text, but never letting it have time to show you the updated text. To make your UI show the changed text, add the Application.DoEvents line like this :

textBox.Text += text;Application.DoEvents();

p.s. : Remove the else block of your If / Else loop, it is redundant, and also as pointed by others there is not any use of creating those 2 Threads as all they are doing is post the message on the UI Thread itself.


You're still performing a single-threaded task, just re-launching it on the UI thread if needed.

for (int i = 0; i < 500; i++){    string text = ""+i;    textBox.BeginInvoke((MethodInvoker)delegate()            {                textBox.Text += text;            });}


The problem is that you're starting a new thread, and then that new thread is doing nothing except adding one new task for the UI thread to process that does a lot of work. To keep your form responsive you need to have time where the UI thread is doing nothing, or at least not spending a significant amount of time doing any one task.

To keep the form responsive we need to have lots of little BeginInvoke (or Invoke) calls.

private void writeText(TextBox textBox, string text){    for (int i = 0; i < 500; i++)    {        Invoke(new MethodInvoker(() =>        {            textBox.Text += text;        }));    }}

By having lots of little invoke calls it allows things like paint events, mouse move/click events, etc. to be handled in the middle of your operations. Also note that I removed the InvokeRequired call. We know that this method will be called from a non-UI thread, so there's no need for it.