我正在做一些有关多线程的任务。 首先,我创建表单1,该表单将使用套接字连接到服务器: clientSocket.Connect("127.0.0.1", 8888);
然后我创建一个线程调用getMessage,它将侦听来自服务器的消息:
ctThread = new Thread(getMessage); ctThread.Start();
和getMessage函数在这里:

while (true)
            {
                serverStream = clientSocket.GetStream();
                byte[] inStream = new byte[10025];
                int buffSize = clientSocket.ReceiveBufferSize;
                serverStream.Read(inStream, 0, buffSize);
                string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                readData = "" + returndata;
                if (readData.IndexOf("$") != -1)
                {
                    readData = readData.Substring(0, readData.IndexOf("$"));
                    newFrm = new Form1();
                    newFrm.doNetworkMethod(readData);
                }
            }

然后我在Form2中创建doNetworkMethod以便Form1将数据发送到Form2,在Load Event Function中的Form2中我有
doNetworkDelegate w = doNetworkMethod; w.BeginInvoke(readData, null, null);

在此之前,我创建了2位代表
public delegate void doNetworkDelegate(string readData); public delegate void displayChatDelegate(string readData);
最后,我创建了2个函数调用:

public void doNetworkMethod(string readData)
    {
        if (readData != null)
        {
            if (!this.IsHandleCreated) this.CreateHandle();
            this.Invoke(new displayChatDelegate(displayChatMethod), new object[] { readData.ToString() });
            Thread.Sleep(1);
        }
    }
    public void displayChatMethod(string readData)
    {
        lock (this)
        {
            textBox1.Text = textBox1.Text + readData;
            textBox2.Text = textBox2.Text + readData; 
        }
    }

但是textBox1textBox2不显示readData内容,但是当我创建MessageBox.show(readData)它会显示。

谢谢你的帮助

===============>>#1 票数:2

您不能在非UI线程中创建UI元素。

您的代码newFrm = new Form1(); getMessage函数中被调用之前,需要先将其编组回UI线程。

  ask by ThanhNguyen translate from so

未解决问题?本站智能推荐: