Ben
Ben

Reputation: 341

How to escape a loop

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();
}

Upvotes: 4

Views: 527

Answers (4)

axel_c
axel_c

Reputation: 6796

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;
      }      
}

Upvotes: 6

jonsca
jonsca

Reputation: 10381

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.

Upvotes: 3

Jim
Jim

Reputation: 1735

Use break to get out of the loop.

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

Upvotes: 0

Sarawut Positwinyu
Sarawut Positwinyu

Reputation: 5042

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.

Upvotes: 0

Related Questions