Reputation: 518
I have the following code which should send a series values through TCP/IP, each value modifies variables 'x', 'y' and 'z' in some way. When I get any response I want the code to display the current value of 'x', 'y' and 'z', but it doesn't. I've tried adding Sleep(), Timers, and even using Labels instead of textBoxes but nothing. Any ideas? Regards
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();
}
Upvotes: 1
Views: 210
Reputation: 71060
I'm guessing that your text box / label / etc is not being given a chance to redraw as the above code is running in the main GUI thread of the application. The thread is busy doing that for loop so it can't process the repaint events. Sleep
doesn't help as it puts the thread being put to sleep is the thread required to do the redraw.
To sort this out, you need to put the above loop into its own thread. This will allow the GUI thread a chance to redraw the controls. You need to use the Invoke method to update the controls as you'll get a cross thread execution error.
Upvotes: 2