“从创建它的线程以外的线程访问。”只有一个线程

时间:2015-03-14 01:47:55

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

2 个答案:

答案 0 :(得分:2)

显然,NetComm.Client.Connected是从另一个线程中提出的。要从其他线程更新您的UI,您可以调用Control.Invoke()

只需将您的事件处理程序代码更改为以下内容:

private void client_Connected()
{
    Action updateUi = () => textBoxChat.AppendText("Connected succesfully!" + Environment.NewLine);
    this.Invoke(updateUi);
}

答案 1 :(得分:0)

通过将代码移动到Form_Load()来解决问题。