我有一个while循环,当我按下按钮时开始。我正在使用它来维护与另一台计算机上的服务的通信。问题是,当我从另一台计算机上收到“已完成”消息时,我需要它打破while循环并停止监听,直到再次按下该按钮。我所做的一切似乎都无法摆脱它。
请注意整个过程都在自己的主题中执行。
我尝试在交换机中第一个案例结束之前放置 break; ,没有这样的运气,我不确定是不是因为它是一个期望中断的switch语句;案件之间或原因是什么。我也试过把 return; 放在那里,但它仍然不会爆发。我最终不得不关闭应用程序并重新启动它以再次使用该按钮。
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);
}
答案 0 :(得分:5)
定义一个布尔变量,该变量将保存您收到"已完成"消息。
如果您要进入下一次迭代,如果此值为true
,那么您就会中断,并且您将退出循环。
示例:
// Abbreviated
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
bool breakTheWhile = false;
switch (data)
{
case "Completed":
// Abbreviated
breakTheWhile = true;
break;
case "FIU":
// Abbreviated
break;
case "DSF":
// Abbreviated
break;
default:
// Abbreviated
break;
}
if (breakTheWhile)
break;
}