我试图逃避一个循环.基本上,如果满足"if"条件,我希望能够退出此循环:
private void CheckLog()
{
while (true)
{
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat"))
continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
<< Escape here - if the "if" condition is met, escape the loop here >>
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Dir*_*irk 72
使用break;逃脱第一循环:
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
break;
}
Run Code Online (Sandbox Code Playgroud)
如果你想要转义第二个循环,你可能需要使用一个标志并检查out循环的守卫:
boolean breakFlag = false;
while (!breakFlag)
{
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
breakFlag = true;
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想从嵌套循环中完全退出函数,请输入return;而不是a break;.
但这些并不是最佳实践.您应该找到一些方法将必要的布尔逻辑添加到您的while警卫中.
break 要么 goto
while ( true ) {
if ( conditional ) {
break;
}
if ( other conditional ) {
goto EndWhile;
}
}
EndWhile:
Run Code Online (Sandbox Code Playgroud)