I am trying to escape a while loop. Basically, if the "if" condition is met, I would like to be able to exit this loop:
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 >> } } } } }
Breaking Out of While Loops. To break out of a while loop, you can use the endloop, continue, resume, or return statement.
You can stop an infinite loop with CTRL + C . You can generate an infinite loop intentionally with while True . The break statement can be used to stop a while loop immediately.
Break Statement in C/C++ The break in C or C++ is a loop control statement which is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stops there and control returns from the loop immediately to the first statement after the loop.
Use break;
to escape the first loop:
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; }
If you want to also escape the second loop, you might need to use a flag and check in the out loop's guard:
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; } } }
Or, if you want to just exit the function completely from within the nested loop, put in a return;
instead of a break;
.
But these aren't really considered best practices. You should find some way to add the necessary Boolean logic into your while
guards.
break
or goto
while ( true ) { if ( conditional ) { break; } if ( other conditional ) { goto EndWhile; } } EndWhile:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With