How do I make cross-threaded calls to a ToolStripStatusLabel?

Maslow picture Maslow · Jul 14, 2009 · Viewed 11.3k times · Source

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;
    }

Answer

Greg D picture Greg D · Jul 14, 2009

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.)