C#线程中字符串无法被赋值???
private void button1_Click(object sender, EventArgs e)
{
threadServer = new Thread(new ThreadStart(accpServer));
threadServer.IsBackground = true;
threadServer.Start();
}
private void accpServer()
{
try
{
Control.CheckForIllegalCrossThreadCalls = false;//取消線程保護
MyServer = new IPEndPoint(myIP, 9999);
sock = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(MyServer);
sock.Listen(50);
while (true)
{
accSock = sock.Accept();
if (accSock.Connected)
{
MessageBox.Show("有客户端成功连接");
}
Byte[] Rec = new Byte[64];
NetworkStream netStream = new NetworkStream(accSock);
netStream.Read(Rec, 0, Rec.Length);
string rec1 =
System.Text.Encoding.BigEndianUnicode.GetString(Rec);
this.textBox1.Text = rec1;
MessageBox.Show("参数1:" + rec1);//这里可以显示rec1的正确值,假如赋值为one
if (textBox1.Text == "one" )//这个的判断结果是正确的,可以进入大括号
{
MessageBox.Show("接收成功");
}
if (rec1 == "one" )//但是这个却得出的判断结果是假,进不去大括号内部
{
MessageBox.Show("接收成功");
}
//}
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
求各位帮帮忙看看这是怎么回事好吗,多谢了,困扰我一天了
------解决方案--------------------
线程中访问界面控件需要做线程同步
参考如下代码:
C# code
public void DoWork()
{
Thread.Sleep(5000);
Invoke(new EventHandler(DoInvoke));
}
private void DoInvoke(object sender, EventArgs e)
{
button1.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
Thread vThread = new Thread(new ThreadStart(DoWork));
vThread.Start();
}