views:

717

answers:

2

I tend to use a StatusStrip at the bottom of most of my applications for simple status updates and occasionally a progress bar.

However, it appears ToolStripStatusLabels do not inherit from control, so they have no .Invoke, or .InvokeRequired. So how would I thread-safe make a call to change it's text property?

Coded answers for posterity and others that come searching:

Action<string> test=(text) =>
   {
    if (this._statusStrip.InvokeRequired) this._statusStrip.Invoke(
      new MethodInvoker(() => this._lblStatus.Text = text));
    else this._lblStatus.Text = text;
   };

or

private void TestInvoker(string text)
 {
  if (this._statusStrip.InvokeRequired) 
            this._statusStrip.Invoke(
       new MethodInvoker(() => this._lblStatus.Text = text));
  else this._lblStatus.Text = text;
 }
+5  A: 

This is a good question!

While ToolStripStatusLabel does not inherit from control, the containing ToolStrip does! Use the containing ToolStrip's Invoke to make calls against the ToolStripStatusLabel.

This is because the ToolStrip manually handles the drawing of its component bits, much the same way that WPF manages the drawing of all of its component bits, without generating a separate handle for each one. This is useful because it's easy to forget that every Control has an associated HANDLE and the system only has a finite number of those to dish out, e.g..

(I've run into this before also. I mentioned it in a sidebar on another question, for example. I should update that text to reflect my more recent understanding.)

Greg D
Yeah, and you could even use the Forms Invoke method as that is created on the same thread. But I would go with Greg D's solution as it's more logical.
sindre j
@sindre, not necessarily, but probably... whereas the ToolStripStatusLabels are necessarilly created on the same thread as the StatusStrip
Charles Bretana
A: 

Also, in general, you do not Have to use the InvokeRequired and BeginInvoke on the exact same control that you are manipulating in code, as long as you can guarantee that the control you are manipulating was created on the same thread (e.g., in the forms' initialization routine), as the UI element you are calling InvokeRequired /BeginInvoke on.

Charles Bretana
ah interesting detail
Maslow