Mental Jetsam

By Peter Finch

Archive for August, 2007

Updating a StatusStrip from a worker thread in C#

Posted by pcfinch on August 9, 2007

I found that when I was trying to update a label and process bar in a StatusStrip from a button click event on a windows form, the status strip was not updating until the end. This is because the button event occurs in the UI thread and, as this is the thread that paints the controls, obviously the control was not getting a chance to redraw itself.

This was solved by placing code for the button event in a worker thread. However, you can not talk directly to a control from a worker thread as controls are not thread-safe by default. C# has nice Invoke() function on controls that let you call a member function in one thread but actually execute it in the thread that belongs to the control by using a delegate. This method works with most controls including TextBoxes.

Ref How to : Make thread-safe calls to windows forms control.

public partial class Main : Form
  delegate void SetStatusCallback(String text, int nPercent);

  private void buttonGo_Click(object sender, EventArgs e)

  private void SetStatus(String text, int nPercent)
    if (statusStrip1.InvokeRequired) {
      SetStatusCallback d = new SetStatusCallback(SetStatus);
      this.Invoke(d, new object[] { text, nPercent } );
    } else {
      labelStatus.Text = text;
      progressStatus.Value = nPercent;

  private void backgroundWorker1_DoWork(
    object sender,
    DoWorkEventArgs e)
    SetStatus("Creating HTTP Request", 20) ;
    SetStatus("Using POST method", 40) ;

Posted in C#.NET | 1 Comment »