开发者

How to escape a loop

开发者 https://www.devze.com 2023-03-14 01:20 出处:网络
I have a while loop in Main() which goes through several methods. Although one method named ScanChanges() has an if / else statement, in the case of if, it must jump to Thread.Sleep(10000) (at the end

I have a while loop in Main() which goes through several methods. Although one method named ScanChanges() has an if / else statement, in the case of if, it must jump to Thread.Sleep(10000) (at the end of the loop)开发者_运维问答.

static void Main(string[] args)
{    
    while (true)
    {
        ChangeFiles();    
        ScanChanges();    
        TrimFolder();    
        TrimFile();    
        Thread.Sleep(10000);
    }
}    

private static void ChangeFiles()
{
    // code here
}

private static void ScanChanges()
{
} 

FileInfo fi = new FileInfo("input.txt");
if (fi.Length > 0)
{
    // How to Escape loop??
}
else
{
    Process.Start("cmd.exe", @"/c test.exe -f input.txt > output.txt").WaitForExit();
}


Make ScanChanges return some value indicating whether you must skip to the end of the loop:

class Program
    {
        static void Main(string[] args)
        {

            while (true)
            {
                ChangeFiles();

                bool changes = ScanChanges();

                if (!changes) 
                {
                    TrimFolder();

                    TrimFile();
                }
                Thread.Sleep(10000);
            }
        }


private static void ChangeFiles()
{
  // code here
}

private static bool ScanChanges()
{
     FileInfo fi = new FileInfo("input.txt");
     if (fi.Length > 0)
     {
         return true;
     }
     else
     {
         Process.Start("cmd.exe", @"/c test.exe -f input.txt > output.txt").WaitForExit();

         return false;
      }      
}


Have ScanChanges return a bool if you've reached that if statement within ScanChanges, and then have another if statement in the while loop that skips over those two procedures if ScanChanges comes back true.


Make the return value out of ScanChanges, it may be boolean if it going to break loop return true else return false.

Then set break loop condition in main.


Use break to get out of the loop.

if (fi.Length > 0)
{
    break;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号