How to update UI control inside Parallel.ForEach ?
-
Hi I am trying to use Parallel.ForEach with ConcurrentBag and it work but to display a feedback I used progessbar control to display fname value , problem after few seconds I get error and the error message is not visible instead a wight box appear because of using a thread . any idea what is the problem in this code ?
int row\_idx = 1; ConcurrentBag<(int, string, float)> bag = new ConcurrentBag<(int, string, float)>(); Parallel.ForEach(elements, element => { string fname = element.name; float ftrack = (float)(element.track); var elementsToAdd = new (int, string, float)\[\] { (row\_idx, fname, fsize) }; bag.Add(elementsToAdd\[0\]); row\_idx++; ProgressBar1.Text = fname; // <<---- error here ProgressBar1.Update(); //Application.DoEvents(); });
-
Hi I am trying to use Parallel.ForEach with ConcurrentBag and it work but to display a feedback I used progessbar control to display fname value , problem after few seconds I get error and the error message is not visible instead a wight box appear because of using a thread . any idea what is the problem in this code ?
int row\_idx = 1; ConcurrentBag<(int, string, float)> bag = new ConcurrentBag<(int, string, float)>(); Parallel.ForEach(elements, element => { string fname = element.name; float ftrack = (float)(element.track); var elementsToAdd = new (int, string, float)\[\] { (row\_idx, fname, fsize) }; bag.Add(elementsToAdd\[0\]); row\_idx++; ProgressBar1.Text = fname; // <<---- error here ProgressBar1.Update(); //Application.DoEvents(); });
That's because you cannot touch a UI control from anything other than the UI (startup) thread. When you use tasks, you're using other threads that are not the UI thread. To change the text of a control, you have to marshal a call to a function back to the UI thread so that function updates the Text property and does it on the correct thread. You can see how it's done at How to make thread-safe calls to controls - Windows Forms .NET | Microsoft Learn[^]
Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles. Dave Kreskowiak
-
That's because you cannot touch a UI control from anything other than the UI (startup) thread. When you use tasks, you're using other threads that are not the UI thread. To change the text of a control, you have to marshal a call to a function back to the UI thread so that function updates the Text property and does it on the correct thread. You can see how it's done at How to make thread-safe calls to controls - Windows Forms .NET | Microsoft Learn[^]
Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles. Dave Kreskowiak
Thanks