Reputation: 21
why when i'm runing the program the for's doesn't run in Parallel after the "one" for is finish the "two" for begin thanks in advance (im a noobie in C#)
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(Threadtest));
t.Start();
for(int i = 0 ;i<5;i++)
richTextBox1.Text = richTextBox1.Text + "one"+i+"\n";
}
private void Threadtest()
{
for (int i = 0; i < 5; i++)
{
MethodInvoker action = delegate { richTextBox1.Text = richTextBox1.Text + "two" + i + "\n"; };
richTextBox1.Invoke(action);
}
}
Upvotes: 2
Views: 272
Reputation: 2799
The GUI environment is single threaded. And there is nothing you can do about it. That is how GUIs in Windows are designed.
Invoke
is only queuing the operations on the GUI thread to be completed after the current operation, button1_Click
, is done.
You can use Appllication.DoEvents
to process anything queued before continuing, but the UI is still single threaded.
Upvotes: 1
Reputation: 4561
EDIT 3: corrected again
The threaded loop is not 'weaving' updates because your non-threaded loop it is not returning control to the main gui event loop, which would process the events from your thread. Thus, it all happens afterwards. One solution to 'see' this happen would be to spawn two threads.
Upvotes: 2
Reputation: 40160
You would need to do it with many more than 5 iterations. The thread isn't even getting fired up before your "one" stuff is completed.
Also, because your "one" code never sleeps, it may run to completion before it allows your marshalled code via Invoke
to run at all. Invoke
/BeginInvoke
cause the code to run on the UI thread - that can't happen until the UI thread has no other work to do.
DoEvents
would enable that. But it's not something you should normally use for multi-threading. It just helps for this illustration of multi-threading.
Upvotes: 3