Reputation: 147
I am using toolStripStatusLabel
in multithreading and although it is another thread which interact with the toolStripStatusLabel
my invokeRequired method of the statusStrip
always return false (I enforce the creation of the handle also). In this thread I can access the toolStripStatusLabel
(from else clause), update it but my editing could not be shown in the main UI. Here is my code:
public void safeThreaded()
{
Form2 form = new Form2();
StatusStrip ss = (StatusStrip)form.Controls["statusStrip1"];
ToolStripStatusLabel label = (ToolStripStatusLabel)ss.Items["toolStripStatusLabel1"];
string text = "Written by the background thread.";
if (!(ss.IsHandleCreated))
{
IntPtr handler = ss.Handle;
}
if (ss.InvokeRequired)
{
ss.Invoke(new updateTextCallback(updateText), new object[]{"Text generated on non-UI thread."});
}
else
{
// It's on the same thread, no need for Invoke
label.Text = text + " (No Invoke)";
MessageBox.Show(label.Text.ToString());
ss.Refresh();
}
}
private void updateText(string text)
{
Form2 form = new Form2();
StatusStrip ss = (StatusStrip)form.Controls["statusStrip1"];
ToolStripStatusLabel label = (ToolStripStatusLabel)ss.Items["toolStripStatusLabel1"];
label.Text = text;
}
public delegate void updateTextCallback(string text);
Upvotes: 1
Views: 2863
Reputation: 4166
It's because the owning thread is whatever thread you're calling safeThreaded()
from - you're creating the Form with the StatusStrip
and ToolStripStatusLabel
, and then editing it all in the same thread.
If you were to create the Form in one thread, and then run your safeThreaded()
function (without creating the Form2
in it) in a separate thread, then you should see InvokeRequired
be true.
Upvotes: 1