Mental Jetsam

By Peter Finch

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)
  {
    backgroundWorker1.RunWorkerAsync();
  }

  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) ;
    ...
  }
}
Advertisements

One Response to “Updating a StatusStrip from a worker thread in C#”

  1. Hello !

    I’m new on this forum so I introduce me…

    My name is Jason I’m 23 years old, I’m Belgian.

    I like: horses and dogs…

    Nice to meet you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: