Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
like image 469
Maslow Avatar asked Jul 14 '09 20:07

Maslow


2 Answers

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

like image 92
Greg D Avatar answered Oct 05 '22 02:10

Greg D


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.

like image 27
Charles Bretana Avatar answered Oct 05 '22 03:10

Charles Bretana