读书人

线程有关问题

发布时间: 2012-01-20 18:53:53 作者: rapoo

线程问题

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ServerProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

IPAddress myIP = IPAddress.Parse("127.0.0.1");
IPEndPoint myServer;
Socket sock;
bool check = true;
Socket accSock;

private void button1_Click(object sender, EventArgs e)
{
try
{
myIP = IPAddress.Parse(this.textBox1.Text);
}
catch (Exception)
{

MessageBox.Show("你的IP格式不正确,请重新输入!");
return;
}
try
{
Thread thread = new Thread(new ThreadStart(accp));
thread.Start();
}
catch (Exception ex)
{

this.textBox3.AppendText(ex.Message);
}
}

private void accp()
{
int port=int.Parse(this.textBox2.Text);
myServer = new IPEndPoint(myIP, port);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(myServer);
sock.Listen(50);
this.textBox3.AppendText("主机:"+this.textBox1.Text+" 端口:"+this.textBox2.Text+" 开始监听..\r\n");
accSock = sock.Accept();
if (accSock.Connected)
{
this.textBox3.AppendText("与客户建立连接\r\n");
while (check)
{
Byte[] rec=new Byte[64];
NetworkStream netStream = new NetworkStream(accSock);
netStream.Read(rec, 0, rec.Length);
string recMsg = System.Text.Encoding.BigEndianUnicode.GetString(rec);
richTextBox1.AppendText(recMsg+"\r\n");
}
}

}

private void button2_Click(object sender, EventArgs e)
{
try
{
Byte[] sendByte=new Byte[64];
string strSend = this.textBox3.Text;
sendByte = System.Text.Encoding.BigEndianUnicode.GetBytes(strSend.ToCharArray());
NetworkStream netStream = new NetworkStream(accSock);
netStream.Write(sendByte, 0, sendByte.Length);
}
catch (Exception)
{

MessageBox.Show("连接尚未建立,无法发送");
}
}

private void button3_Click(object sender, EventArgs e)
{
try
{
sock.Close();
this.textBox3.AppendText("主机:" + this.textBox1.Text + " 端口:" + this.textBox2.Text + " 开始监听..\r\n");
}
catch (Exception)
{



MessageBox.Show("监听尚未开始,关闭无效");
}
}



}
}




为什么会报这个错误啊,"Cross-thread operation not valid: Control 'textBox3' accessed from a thread other than the thread it was created on."

[解决办法]
你的代码我没看

你的错误显然说明你的操作涉及了跨线程操作

你应该用事件+委托来操作,你这样赋值肯定不行的。!

读书人网 >.NET

热点推荐