C++ – Update statusbar from a thread using C++/CLI

c++-climultithreadingwinforms

I'm sure this is a pretty straight forward question. I'm writing a small windows forms app using C++/CLI. When the form initializes, I start a thread that will process some code. When the code in the thread is executed, I want the thread to somehow update the text in a statusbar in the bottom of the window. So I was thinking something like this:

  1. I create an event.
  2. Then I create the Thread that will do some processing.
  3. When the processing is done, fire an event that makes the text in the statusbar update.

Is this a reasonable way to go? If so, how do I update the statusbar from within the thread? Maybe there is a smarter way to acheive this?

Best Answer

Declare a method like that changes the status text given a string:

private: void UpdateStatus(String^ msg) {
    statusBar.Text = msg;
}

and from the other thread, use Invoke:

Invoke(gcnew Action<String^>(this, &Form1::UpdateStatus), "message");

Invoke will call the given delegate with the specified parameters on the UI thread.