I am trying to implement a Parallel.ForEach loop to replace the old foreach loop, but I am having problems updating my user interface (I have a counter showing something like "processed x / y files"). I made an example of a Parallel.For loop to illustrate my problem (label not updating).
using System; using System.Windows.Forms; using System.Threading.Tasks; using System.Threading; namespace FormThreadTest { public partial class Form1 : Form { private SynchronizationContext m_sync; private System.Timers.Timer m_timer; private int m_count; public Form1() { InitializeComponent(); m_sync = SynchronizationContext.Current; m_count = 0; m_timer = new System.Timers.Timer(); m_timer.Interval = 1000; m_timer.AutoReset = true; m_timer.Elapsed += new System.Timers.ElapsedEventHandler(m_timer_Elapsed); m_timer.Start(); } private void m_timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { Task.Factory.StartNew(() => { m_sync.Post((o) => { label1.Text = m_count.ToString(); Application.DoEvents(); }, null); }); } private void button1_Click(object sender, EventArgs e) { Task.Factory.StartNew(() => { Parallel.For(0, 25000000, delegate(int i) { m_count = i; }); }); } } }
If I change the button event event method and add Thread.Sleep (), it seems that the time for updating the UI thread does its job:
private void button1_Click(object sender, EventArgs e) { Task.Factory.StartNew(() => { Parallel.For(0, 25000000, delegate(int i) { m_count = i; Thread.Sleep(10); }); }); }
Is there a way to avoid sleep, or do I need to eat it there? It seems that my ui will not update the shortcut if I do not? which I find strange, since I can move the application window (it doesnโt block) - so why not replace the shortcut and how can I change my code to better support Parallel.For updates (each) and UI?
I was looking for a solution, but I can not find anything (or maybe I was looking for the wrong thing?).
Relationship Simon
source share