1
我在多線程中使用toolStripStatusLabel
,雖然它是另一個與toolStripStatusLabel
交互的線程,我的statusStrip
的invokeRequired方法總是返回false(我也強制創建句柄)。在這個線程中,我可以訪問toolStripStatusLabel
(從else子句),更新它,但是我的編輯無法顯示在主UI中。這裏是我的代碼:toolStripStatusLabel在多線程中
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);