跨线程操作无效

时间:2010-02-12 23:01:23

标签: 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);
    }
}

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

4 个答案:

答案 0 :(得分:22)

你需要替换它:

richTextBoxReceivedMsg.AppendText(szData);

类似

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

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

答案 1 :(得分:2)

查看Jon Skeet关于多线程的文章,特别是multi-threading winforms上的页面。它应该能解决你的问题。

答案 2 :(得分:0)

This链接可以为您提供帮助。

答案 3 :(得分:-1)

通过在f​​orm1()构造函数中写入给定语句来检查RichTextBox.CheckForIllegalCrossThreadCalls = false;

谢谢你......

相关问题