日期:2014-05-18  浏览次数:20694 次

socket聊天如何将收到的信息更新到窗口?
下面是我改的一部分接收用的代码,但是修改form中textbox的时候会线程不对,,,求助啊啊

Thread Listener = new Thread(new ThreadStart(ReceiveMsg));
  Listener.Start();

接收信息的:
  public void ReceiveMsg()
  {
  while (true)
  {
  lock (this)
  {
  IAsyncResult iar = udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);
  receiveDone.WaitOne();
  Thread.Sleep(100);
  }
  }
  }

  private void ReceiveCallback(IAsyncResult iar)
  {
  UdpState udpReceiveState = iar.AsyncState as UdpState;
  if (iar.IsCompleted)
  {
  Byte[] receiveBytes = udpReceiveState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);
  receiveString = Encoding.ASCII.GetString(receiveBytes);
  MessageBox.Show(receiveString);
  AppendText(receiveString);《-----这里是修改textbox
  receiveDone.Set();
  }
  }

------解决方案--------------------
C# code

 private delegate void AppendTextToRichTextBoxDelegate(string message);
        private void AppendTextToRichTextBox(string message)
        {
            if (rtxtReceive.InvokeRequired)
            {
                AppendTextToRichTextBoxDelegate d = new AppendTextToRichTextBoxDelegate(AppendTextToRichTextBox);
                rtxtReceive.Invoke(d, message);
            }
            else
            {
                rtxtReceive.AppendText= message;
            }
        }