2011-10-12 133 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或控制)