2013-04-24 61 views
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); 

回答

1

這是因爲擁有線程是什麼線程你打電話從safeThreaded() - 你創建與StatusStripToolStripStatusLabel,然後將表格進行編輯都在同一個線程。

如果您要創建一個線程的窗體,然後運行safeThreaded()功能(沒有創建Form2),則它在一個單獨的線程,那麼你應該看到InvokeRequired是真實的。