gpt4 book ai didi

c# - 跨线程操作无效

转载 作者:太空狗 更新时间:2023-10-29 20:47:06 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com