I have a while loop that begins when I press a button. I'm using it to maintain communication with a service on another computer. The problem is that when I get the "Completed" message back from the other computer I need it to break out of the while loop and stop listening till the button is pressed again. Nothing I do seems to break it out of the loop.
Please note the entire process is executed in its own thread.
I tried putting break; just before the end of the first case in the switch, no such luck and I'm not sure if it's because it's a switch statement that expects a break; between cases or what the reason is. I also tried putting return; in there but it still won't break out. I end up having to close the application and restart it to use the button again.
TcpClient client = new TcpClient(serverIP, 11000);
NetworkStream stream = client.GetStream();
Byte[] bytes = new Byte[256];
String data = null;
int i;
stream.Write(copy, 0, copy.Length);
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//MessageBox.Show(data);
switch (data)
{
case "Completed":
this.Invoke((MethodInvoker)delegate
{
progressBar1.Value = 0;
progressBar1.Visible = false;
progressBar1.Update();
if (prod)
{
sqlLink.setProdFile(imageName, destFileName);
} else
{
sqlLink.setTestFile(imageName, destFileName);
if (sqlLink.getTestVM(imageName) != "")
{
if (message.Text("Test VM", "Power on specified Virtual Machine in private mode?", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
PS ps = new PS();
ps.powerOnVM(sqlLink.getTestVM(imageName));
}
}
}
//Tried putting break; here.
});
break;
case "FIU":
{
progressBar1.Value = 0;
progressBar1.Visible = false;
progressBar1.Update();
message.Text("Error", "The image is in use. Try shutting down machines or unassigning devices.", MessageBoxButtons.OK);
}
break;
case "DSF":
{
progressBar1.Value = 0;
progressBar1.Visible = false;
progressBar1.Update();
message.Text("Error", "Drive space is full on production volume. Try deleting some older images.", MessageBoxButtons.OK);
}
break;
default:
this.Invoke((MethodInvoker)delegate
{
progressBar1.Value = Int16.Parse(data);
progressBar1.Update();
});
break;
}
}
stream.Close(); //This never happens.
client.Close();
}
catch (Exception ex)
{
message.Text("Error", "Copy Method Error: " + ex.Message, MessageBoxButtons.OK);
}