Form1://假设窗体class 名字为Form1 增加 delegate void SetTextCallback(string text);public void SetData(string data) { SetText(data); } private void SetText(string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } } 修改: //Thread clientService = new Thread(new ThreadStart(p.ProcessClient)); Thread clientService = new Thread(p.ProcessClient); clientService.IsBackground = true; //clientService.Start(); clientService.Start(this); // public void ProcessClient() public void ProcessClient(object o) { Form1 f = (Form1)o; _byteReceive = new byte[140]; NetworkStream ns = new NetworkStream(_currentSocket); int nReceiveCount = ns.Read(_byteReceive, 0, _byteReceive.Length); _strReceive = Encoding.ASCII.GetString(_byteReceive, 0, nReceiveCount);//收到的内容 // Console.WriteLine(_strReceive); f.SetData(_strReceive); }
Control.CheckForIllegalCrossThreadCalls=false;
或者使用代理
Form1://假设窗体class 名字为Form1
增加
delegate void SetTextCallback(string text);public void SetData(string data)
{
SetText(data);
}
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
修改:
//Thread clientService = new Thread(new ThreadStart(p.ProcessClient));
Thread clientService = new Thread(p.ProcessClient); clientService.IsBackground = true;
//clientService.Start();
clientService.Start(this);
// public void ProcessClient()
public void ProcessClient(object o) {
Form1 f = (Form1)o;
_byteReceive = new byte[140];
NetworkStream ns = new NetworkStream(_currentSocket); int nReceiveCount = ns.Read(_byteReceive, 0, _byteReceive.Length);
_strReceive = Encoding.ASCII.GetString(_byteReceive, 0, nReceiveCount);//收到的内容 // Console.WriteLine(_strReceive);
f.SetData(_strReceive);
}
不用new?
new 就返回不到创建线程的窗体了。