跨线程操作无效。

5

我正在尝试访问另一个窗体上的富文本框,我使用以下代码进行操作:

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”,但它会陷入一个连续循环并引发堆栈溢出错误。
谢谢 霍拉汉

尝试过使用window.InvokeRequired而不是window.RichTextBox1.InvokeRequired了吗? - Olivier Jacot-Descombes
是的,那只是跳转到else语句,然后抛出异常 :/ - Houlahan
你确定控件句柄已经创建了吗?即使你确定了,再检查一遍也不会有坏处... - jmoreno
3个回答

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

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而不是Invoke。虽然我期望,正如另一个帖子所提到的,您应该使用与所需检查相同的内容来调用。(即窗口.invokeRequired和窗口.BeginInvoke或控件)

0

我在你的代码中没有看到任何错误。你可能需要检查一下在更新RichTextBox时是否触发了任何事件,它们可能会导致跨线程问题。

作为解决方案,使用对象来处理问题,你遇到跨线程问题的可能性会更小。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接