2015-06-25 62 views
0

執行tcViewer.TabPages.Add(t)語句時獲取交叉線程錯誤。獲取交叉線程錯誤甚至使用調用

代碼如下。

Private Function fff(t As TabPage) 
    tcViewer.TabPages.Add(t) 'giving cross thread error 
End Function 

Function WebBrowserThread() 
    Dim t As TabPage = New TabPage((k + 1).ToString()) 
    t.Name = k.ToString() 
    tcViewer.Invoke(fff(t)) 
End Function 

請指導。

回答

-2

我不知道你會得到什麼調用錯誤,但我建議禁用跨線程通過(使用API​​打交道時非常有用)在構造或加載事件增加這個檢查

Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False 

入住這http://tech.xster.net/tips/invoke-ui-changes-across-threads-on-vb-net/

在WPF這樣的問題

很容易解決,因爲你有一個線程的所有控件(Dispatcher.Invoke

更新

處理的UI控件必須在UI線程

Me.Invoke(sub() 
      Dim t As TabPage = New TabPage((k + 1).ToString()) 
      t.Name = k.ToString() 
      fff(t) 
      End Sub) 




    Me.Invoke(sub() 
       tcViewer.TabPages.Add(t) 
      End Sub) 
+0

在WIN窗體中,設置交叉線程檢查錯誤,但得到相同的錯誤,如下所示:'在一個線程上創建的控件不能用於不同線程上的控件。'你知道如何使用tab控件的Invoke來添加標籤頁嗎? – dsi

+0

嘗試此> Me.Invoke(子() 昏暗T作爲TabPage的=新的TabPage((K + 1)的ToString()) t.Name = k.ToString() FFF(噸) 完子) – bigworld12

+0

@ bigworld12如果你打算建議使用CheckForIllegalCrossThreadCalls = False,那麼你應該指出,它可能會導致明顯的隨機崩潰,這將很難調試。 –

1

我想你應該移到新TabPage的創建到UI線程以及上:

Private Function fff(k as Integer) 
    Dim t As TabPage = New TabPage((k + 1).ToString()) 
    t.Name = k.ToString() 
    tcViewer.TabPages.Add(t) 
End Function 

Function WebBrowserThread() 
    tcViewer.Invoke(fff(k)) 
End Function 

當你構建TabPage,你最終達到這個調用堆棧:

System.Windows.Forms.dll!System.Windows.Forms.Control.CreateHandle() 
System.Windows.Forms.dll!System.Windows.Forms.Application.MarshalingControl.MarshalingControl() 
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.MarshalingControl.get() 
System.Windows.Forms.dll!System.Windows.Forms.WindowsFormsSynchronizationContext.WindowsFormsSynchronizationContext() 
System.Windows.Forms.dll!System.Windows.Forms.WindowsFormsSynchronizationContext.InstallIfNeeded() 
System.Windows.Forms.dll!System.Windows.Forms.Control.Control(bool autoInstallSyncContext) 
System.Windows.Forms.dll!System.Windows.Forms.ScrollableControl.ScrollableControl() 
System.Windows.Forms.dll!System.Windows.Forms.Panel.Panel() 
System.Windows.Forms.dll!System.Windows.Forms.TabPage.TabPage() 
System.Windows.Forms.dll!System.Windows.Forms.TabPage.TabPage(string text) 

此時,正在創建Handle,一d如果你是在錯誤的線程上執行該操作,則其他一切都將開始出錯(因爲創建控件的線程不會運行消息泵)