我有以下代码,它应该通过TCP / IP发送一系列值,每个值以某种方式修改变量'x','y'和'z'。当我得到任何响应时,我希望代码显示'x','y'和'z'的当前值,但事实并非如此。我已经尝试添加Sleep(),Timers,甚至使用Labels而不是textBoxes,但没有。有任何想法吗?此致
for (i = 0; i < cant; i++)
{
byte[] data = null;
aux = (Convert.ToInt32(v[i, 3] + 48, CultureInfo.InvariantCulture));
//update variables' values
x = x + Convert.ToInt32(v[i, 0]);
y = y + Convert.ToInt32(v[i, 1]);
z = z + Convert.ToInt32(v[i, 2]);
data = System.BitConverter.GetBytes(aux);
NetworkStream stream = client.GetStream();
// String to store the response ASCII representation.
String responseData = String.Empty;
// Send the message to the connected TcpServer.
stream.Write(data, 0, 1);
// Buffer to store the response bytes.
data = new Byte[256];
while (responseData.Length == 0)
{
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
}
//DISPLAY CURRENT VALUES
textBoxX.Text = x.ToString();
textBoxY.Text = y.ToString();
textBoxZ.Text = z.ToString();
}
答案 0 :(得分:2)
我猜你的文本框/标签/等没有机会重绘,因为上面的代码在应用程序的主GUI线程中运行。线程忙着为循环做这个,所以它不能处理重绘事件。 Sleep
没有帮助,因为它使进入休眠状态的线程是重绘所需的线程。
要对此进行排序,您需要将上面的循环放入其自己的线程中。这将允许GUI线程重绘控件。您需要使用Invoke方法更新控件,因为您将遇到跨线程执行错误。