c# - 跨线程操作无效

标签 c# winforms sockets multithreading

我调试的时候一直报如下错误。

Cross-thread operation not valid: Control 'richTextBoxReceivedMsg' accessed from a thread other than the thread it was created on.

这是它指向的代码:

public void OnDataReceived(IAsyncResult asyn)
{
    try
{
    SocketPacket socketData = (SocketPacket)asyn.AsyncState;

    int iRx  = 0;

        // Complete the BeginReceive() asynchronous call by EndReceive() method
        // which will return the number of characters written to the stream by the client
        iRx = socketData.m_currentSocket.EndReceive (asyn);

        char[] chars = new char[iRx +  1];
        System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
        int charLen = d.GetChars(socketData.dataBuffer, 0, iRx, chars, 0);
        System.String szData = new System.String(chars);
        richTextBoxReceivedMsg.AppendText(szData);

        // Continue the waiting for data on the Socket
        WaitForData( socketData.m_currentSocket);
    }
    catch (ObjectDisposedException)
    {
        System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
    }
    catch (SocketException se)
    {
        MessageBox.Show(se.Message);
    }
}

有人可以帮我解决这个问题吗?

最佳答案

你需要替换这个:

richTextBoxReceivedMsg.AppendText(szData);

用类似的东西

Invoke(new Action(() => richTextBoxReceivedMsg.AppendText(szData)));

原因是 Windows 窗体并非真正设计用于跨不同线程工作。 Invoke 方法将运行您在 UI 线程中传递给它的委托(delegate)。如果您想通过其他线程操作 UI 元素,则必须在 UI 线程上运行实际操作。 InvokeRequired 属性会告诉您何时需要使用 Invoke 而不是直接调用该方法。

关于c# - 跨线程操作无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2255693/

相关文章:

c# - printdialog.showdialog();在 64 位 Windows 7 中不显示打印对话框

c# - 在表单上异步添加组件

c - 我如何使用c套接字程序显示客户端地址?

java - 使用外部机器的 URL 和端口打开 Socket 来播放流音频的安全问题

c# - WebApi 创建无法从 Xamarin.Android 运行的用户

c# - Crystal Reports 版本 13.0 中报告失败错误?

c# - base.OnStartup(e) 是做什么的?

c# - 为每个构建配置设置不同的 ApplicationIcon

c# - 在 C# 中使用 .Show() 方法后,由于循环而导致对话框无法正确显示

javascript - 将数据从网站发送到 C# 表单应用程序