C# &引用;从创建它的线程以外的线程访问;只有一根线
尝试执行以下操作时:C# &引用;从创建它的线程以外的线程访问;只有一根线,c#,C#,尝试执行以下操作时: textBoxChat.AppendText("Connected succesfully!" + Environment.NewLine); 我得到以下错误: An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code Additional information: Cr
textBoxChat.AppendText("Connected succesfully!" + Environment.NewLine);
我得到以下错误:
An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code
Additional information: Cross-thread operation not valid: Control 'textBoxChat' accessed from a thread other than the thread it was created on.
If there is a handler for this exception, the program may be safely continued.
但我只有一根线
编辑:
与错误相关的所有代码:
public partial class FormMain : Form
{
public string ip, port;
NetComm.Client client = new NetComm.Client();
public FormMain()
{
InitializeComponent();
client.Connected += new NetComm.Client.ConnectedEventHandler(client_Connected);
}
private void client_Connected()
{
textBoxChat.AppendText("Connected succesfully!" + Environment.NewLine);
}
}
通过将代码移动到表单_Load(),问题得以解决。显然,
NetComm.Client.Connected
是从另一个线程引发的。要从其他线程更新UI,可以调用
只需将事件处理程序代码更改为如下内容:
private void client_Connected()
{
Action updateUi = () => textBoxChat.AppendText("Connected succesfully!" + Environment.NewLine);
this.Invoke(updateUi);
}
错误很明显。您正在从另一个线程调用一个方法。背景工作者?等待方法?显然,
NetComm.Client
正在另一个线程上引发事件。如果您没有编写该类,请参阅文档。如果您这样做了,请向我们展示事件是如何引发的。查看@mikez是否正确的一种方法是在事件处理程序中放置一个断点。触发断点时,选择Debug
->Windows
->Threads
。