线程操作出现错误,请求支招?

chp845 2011-08-09 02:11:43
  public partial class Form1 : Form
{
private IPAddress myIP = IPAddress.Parse("127.0.0.1");
private IPEndPoint MyServer;
private Socket sock;
private bool check = true;
private Socket accSock;
public Form1()
{
InitializeComponent();
}

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

}

private void button1_Click(object sender, EventArgs e)
{
try
{
myIP = IPAddress.Parse(textBox1.Text);
}
catch
{
MessageBox.Show("您输入的IP地址格式不正确,请重新输入!");
}
try
{
Thread thread=new Thread(new ThreadStart(accp));
thread.Start();
}
catch (Exception ex)
{
textBox3.AppendText(ex.Message);
}
}

点击button1后,出现错误:
线程间操作无效:从不是创建控件“textBox3”的线程访问它,
...全文
72 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
chp845 2011-08-18
  • 打赏
  • 举报
回复
明白了,线程不支持跨控件操作!!!
why 2011-08-09
  • 打赏
  • 举报
回复
最简单的
添加个这个2005里面
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
run_bizi 2011-08-09
  • 打赏
  • 举报
回复
C#控件是不能夸线程访问的,如果要访问就必须使用委托
杨友山 2011-08-09
  • 打赏
  • 举报
回复
要写委托呢

private delegate void accpDelegate();
private void accp()
{
if (!this.InvokeRequired)
{
try
{
MyServer = new IPEndPoint(myIP, Int32.Parse(textBox2.Text));
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(MyServer);
sock.Listen(50);
textBox3.AppendText("主机" + textBox1.Text + "端口" + textBox2.Text + "开始监听.....\r\n");
accSock = sock.Accept();
if (accSock.Connected)
{
textBox3.AppendText("与客户建立连接");
while (check)
{
Byte[] rec = new Byte[64];
NetworkStream netStream = new NetworkStream(accSock);
netStream.Read(rec, 0, rec.Length);
string recMessage = System.Text.Encoding.BigEndianUnicode.GetString(rec);
richTextBox1.AppendText(recMessage + "\r\n");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
this.Invoke(new accpDelegate(accp) );
}

}
chp845 2011-08-09
  • 打赏
  • 举报
回复
请求帮助了呀!求救了呀!

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧