简体   繁体   English

跨线程操作无效

[英]Cross-thread operation not valid

I keep getting the following error when debugging. 调试时我一直收到以下错误。

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

Here's the code that it points to: 这是它指向的代码:

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);
    }
}

Can somebody please help me fix this? 有人可以帮我解决这个问题吗?

You need to replace this: 你需要替换这个:

richTextBoxReceivedMsg.AppendText(szData);

with something like 喜欢的东西

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

The reason is that Windows Forms is not really designed to work across different threads. 原因是Windows Forms并非真正设计为跨不同的线程工作。 Invoke method will run the delegate you pass to it in the UI thread. Invoke方法将运行您在UI线程中传递给它的委托。 If you want to manipulate UI elements via other threads, you'll have to run the actual manipulation on the UI thread. 如果要通过其他线程操作UI元素,则必须在UI线程上运行实际操作。 InvokeRequired property will tell you when you need to use Invoke rather than calling the method directly. InvokeRequired属性将告诉您何时需要使用Invoke而不是直接调用该方法。

Check out Jon Skeet's article on multi-threading, particularly the page on multi-threading winforms . 查看Jon Skeet关于多线程的文章,特别是关于多线程winforms的页面。 It should fix you right up. 它应该能解决你的问题。

链接可能能够帮助您。

check by writing the given statement in your form1() constructor RichTextBox.CheckForIllegalCrossThreadCalls = false; 通过在form1()构造函数中写入给定语句来检查RichTextBox.CheckForIllegalCrossThreadCalls = false;

Thank u.... 感谢你....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM