Ankush Jain Ankush Jain - 2 months ago 22
C# Question

Task.Parallel updating UI. Why So?

I am able to update UI from code 1 but not from 2.

Code 1

Parallel.ForEach(names, name =>
{
lblText.Text += "\n" + name + " Thread " + Thread.CurrentThread.ManagedThreadId;
});


Code 2

Task.Factory.StartNew(() =>
{
Parallel.ForEach(names, name =>
{
lblText.Text += "\n" + name + " Thread " + Thread.CurrentThread.ManagedThreadId;
});
});


I know that code 2 won't update UI because its a secondary thread. But why code 1 is updating UI? Don't Parallel foreach run different threads? if yes then why it is updating UI?

output of code 1

enter image description here

Answer

Both code segments work... Really.

The problem is that the first code block runs while it blocks the UI thread. The second code block starts the task and then continues.

The problem isn't in the use of multiple threads, since both examples use multiple threads to change the value of the label. The problem is in the state of the form.

I assume you run the code in the form constructor. In the first case, there is no handle created, so the operation doesn't need the UI thread. It just updates the backing value. In the second case, in the split millisecond it needs to create the task, it creates the handle for the form. When it needs to update the label the operation needs the UI thread.

If you put in a Wait on the task you will see it will also work. If you move the code to the OnHandleCreated, it both statements will fail.

Comments