C# 如何在C中跳出while循环#

C# 如何在C中跳出while循环#,c#,.net,windows,C#,.net,Windows,我正试图逃离一个短暂的循环。基本上,如果满足“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.

我正试图逃离一个短暂的循环。基本上,如果满足“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 >>
                }
            }
        }
    }
}
private void CheckLog()
{
while(true)
{
睡眠(5000);
如果(!System.IO.File.Exists(“Command.bat”))
继续;
使用(System.IO.StreamReader sr=System.IO.File.OpenText(“Command.bat”))
{
字符串s=“”;
而((s=sr.ReadLine())!=null)
{
如果(s.Contains)(“mp4:生产/捕获/”)
{
RemoveEXELog();
过程p=新过程();
p、 StartInfo.WorkingDirectory=“dump”;
p、 StartInfo.FileName=“test.exe”;
p、 StartInfo.Arguments=s;
p、 Start();
>
}
}
}
}
}

使用
中断要退出第一个循环:

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;
}
如果还想跳出第二个循环,可能需要使用标志并签入输出循环的保护:

        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;
                    }
                }
            }
或者,如果您只想从嵌套循环中完全退出函数,请输入一个
返回而不是
中断


但这些并不是真正的最佳实践。您应该找到一些方法将必要的布尔逻辑添加到
while
保护中

中断
转到

while ( true ) {
  if ( conditional ) {
    break;
  }
  if ( other conditional ) {
    goto EndWhile;
  }
}
EndWhile:

你想退出哪个循环?一个简单的
中断将退出内部循环。对于外部循环,可以使用外部循环作用域变量(例如,boolean exit=false;),该变量在中断内部循环之前设置为true。内环块后,检查退出值,如果为真,则使用
break

“中断”是一个从“最近”循环中断的命令

虽然break有很多很好的用途,但如果不需要的话就不应该使用它——它可以被看作是使用goto的另一种方式,goto被认为是不好的

例如,为什么不:

while (!(the condition you're using to break))
        {
         //Your code here.
        }
如果您使用“break”的原因是不想继续执行循环的该迭代,那么您可能需要使用“continue”关键字,它会立即跳到循环的下一个迭代,无论是while还是for

while (!condition) {
   //Some code
   if (condition) continue;
   //More code that will be skipped over if the condition was true
}

如果您需要继续使用其他逻辑,请使用

break;
或者如果您要返回一个值

return my_value_to_be_returned;
private void CheckLog()
        {
            bool continueLoop = true;
            while (continueLoop)
            {
                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 (continueLoop && (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();
                            continueLoop = false;
                        }
                    }
                }
            }
        }
然而,看看你的代码,我相信你会用下面修改过的例子来控制循环,而不用中断或返回

return my_value_to_be_returned;
private void CheckLog()
        {
            bool continueLoop = true;
            while (continueLoop)
            {
                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 (continueLoop && (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();
                            continueLoop = false;
                        }
                    }
                }
            }
        }

但是你也可能想研究一下。

很抱歉necro添加了一些东西,但我真的很想在现有答案中插入一些缺失的东西(对于像我这样通过谷歌偶然发现这个问题的人):重构你的代码。它不仅使它更易于阅读/维护,而且通常会完全消除这些类型的控制路由问题

如果我必须对上述函数进行编程,我会倾向于这样做:

private const string CatchupLineToIndicateLogDump = "mp4:production/CATCHUP/";
private const string BatchFileLocation = "Command.bat";

private void CheckLog()
{
    while (true)
    {
        Thread.Sleep(5000);
        if (System.IO.File.Exists(BatchFileLocation))
        {
            if (doesFileContainStr(BatchFileLocation, CatchupLineToIndicateLogDump))
            {
                RemoveLogAndDump();
                return;
            }
        }
    }
}

private bool doesFileContainStr(string FileLoc, string StrToCheckFor)
{
  // ... code for checking the existing of a string within a file
  // (and returning back whether the string was found.)
}

private void RemoveLogAndDump()
{
  // ... your code to call RemoveEXELog and kick off test.exe
}

break不起作用?@David-是的,如果OP试图退出外循环,这是使用
goto
是一个好主意的罕见案例之一。@Yakimych胡说:)不幸的是,C#没有一个标记的break,它比
goto
@pst更好地处理这一问题,什么是标记的break,它如何优于goto?@David Heffeman标记的break是一些国家支持的
goto
的子集像Java这样的语言——标签是控制结构的一部分,比如
while
。它与转到的不同之处在于,它只能“突破”该结构,因此,在所有不需要转到的全部“力量”的情况下,更容易遵循。代码不能随意跳转,但是中断可以选择从哪个(可能是嵌套的)循环中断。
goto
的问题/力量在于它太不受限制了。+1不适合考虑两个循环(不提4个字母的关键字)。只有教条主义者才会认为break是坏的。所有的关键词都可能用得不好。所有的关键词都可以很好地使用。
Goto
是一件令人敬畏的事情。@Dementic-并非所有情况下都是如此。如果使用得当,它可以提高可读性,有助于退出深度嵌套的循环,将控制权转移到特定的开关箱标签等。如zellio在上面的示例中所示,它有助于退出,而无需使用任何其他变量等“goto的一个常见用法是将控制权转移到特定的开关箱标签或开关语句中的默认标签。goto语句对于摆脱深度嵌套的循环也很有用。“当我们在“while”循环中使用“switch”关键字时,它不起作用,所以只需在while中添加另一个测试条件,例如bool bTurnOff=false;while(true&&bTurnOff==false){…}@Bobby有趣的方法