title: c# Parallel.For and UI updating?
body: <p>I am trying to implement a Parallel.ForEach loop to replace an old <code>foreach</code> loop, but I am having trouble updating my UI (i have a counter showing something like 'x/y files processed'). I have made a Parallel <code>Forloop</code> example to illustrate my problem (the label is not being updated).</p>
  
  <pre><code>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(() =&gt;
              {
                  m_sync.Post((o) =&gt;
                  {
                      label1.Text = m_count.ToString();
                      Application.DoEvents();
                  }, null);
              });
          }
  
          private void button1_Click(object sender, EventArgs e)        
          {     
              Task.Factory.StartNew(() =&gt;
              {
                  Parallel.For(0, 25000000, delegate(int i)
                  {
                      m_count = i;
                  });
              });
          }
      }
  }
  </code></pre>
  
  <p>If I change the button click event method, and add a Thread.Sleep() it seems to give time for the UI updating thread to do its job:</p>
  
  <pre><code>private void button1_Click(object sender, EventArgs e)        
          {     
              Task.Factory.StartNew(() =&gt;
              {
                  Parallel.For(0, 25000000, delegate(int i)
                  {
                      m_count = i;
                      Thread.Sleep(10);
                  });
              });
          }
  </code></pre>
  
  <p>Is there no way of avoiding the sleep, or do I need to have it there? it seems like my ui won't update the label unless I do? which I find strange, since I can move the application window (it doesn't lock up) - so why won't the label update, and how can I alter my code to better support Parallel.For(Each) and UI updates?</p>
  
  <p>I've been searching for a solution, but I can't seem to find anything (or I maybe searching for the wrong thing?).</p>
  
  <p>Regards
  Simon</p>