2011-10-12 132 views
5

我嘗試使用下面的代碼這樣做訪問的另一種形式的IM豐富的文本框:跨線程操作無效

Private Delegate Sub StringDelegateChat(text As String, window As ChatWindow) 
    Private Sub AppendTextChatWindows(text As String, window As ChatWindow) 
     Try    
      If window.RichTextBox1.InvokeRequired Then 
       window.Invoke(New StringDelegateChat(AddressOf AppendTextChatWindows), text, window) 
      Else 
       window.RichTextBox1.AppendText(text) 
       window.RichTextBox1.SelectionStart = window.RichTextBox1.Text.Length 
       window.RichTextBox1.ScrollToCaret() 
      End If 
     Catch ex As Exception 
      MessageBox.Show(ex.ToString) 
     End Try 
    End Sub 

,但我得到了跨線程操作無效的錯誤,我認爲它這樣做因爲它漏掉了if語句的window.invoke部分。我也嘗試將If window.RichTextBox1.InvokeRequired Then替換爲If InvokeRequired Then,但它會被連續循環捕獲,並引發堆棧溢出錯誤。

感謝 Houlahan

+0

已嘗試window.InvokeRequired而不是window.RichTextBox1.InvokeRequired? –

+0

是的,只是跳到其他,然後拋出異常:/ – Houlahan

+0

你確定控件句柄已經創建?即使你是,也許不會受到雙重檢查...... – jmoreno

回答

6

我相信,在第5行,window.Invoke應改爲window.RichTextBox1.Invoke

Private Delegate Sub StringDelegateChat(text As String, window As ChatWindow) 
Private Sub AppendTextChatWindows(text As String, window As ChatWindow) 
    Try 
     If window.RichTextBox1.InvokeRequired Then 
      window.RichTextBox1.Invoke(New StringDelegateChat(AddressOf AppendTextChatWindows), text, window) 
     Else 
      window.RichTextBox1.AppendText(text) 
      window.RichTextBox1.SelectionStart = window.RichTextBox1.Text.Length 
      window.RichTextBox1.ScrollToCaret() 
     End If 
    Catch ex As Exception 
     MessageBox.Show(ex.ToString) 
    End Try 
End Sub 
0

我看不到您的代碼中的任何錯誤。您可能需要檢查更新RichTextbox時觸發的任何事件。它們可能會導致交叉線程。

作爲解決您的問題的一種解決方法,使用對象時,您不太可能遇到交叉線程問題。

3

你試過:

Private Sub AppendTextChatWindows(text As String, window As ChatWindow) 
     Try    
      If window.RichTextBox1.InvokeRequired Then 
       window.RichTextBox1.BeginInvoke(New StringDelegateChat(AddressOf AppendTextChatWindows), text, window) 
       Exit Sub 
      Else 
       window.RichTextBox1.AppendText(text) 
       window.RichTextBox1.SelectionStart = window.RichTextBox1.Text.Length 
       window.RichTextBox1.ScrollToCaret() 
      End If 
     Catch ex As Exception 
      MessageBox.Show(ex.ToString) 
     End Try 
    End Sub 

基本上,我問的BeginInvoke,而不是調用。儘管我希望,正如另一張海報所提到的,你應該使用同樣的東西來檢查所需的反對。 (即都window.invokeRequired & window.BeginInvoke或控制)