简体   繁体   中英

Does this code loop infinitely?

I have the following code, does this run an endless loop?
I am trying to schedule something every minute and the console application should run continuously until I close it.

class Program
{
  static int curMin;
  static int lastMinute = DateTime.Now.AddMinutes(-1).Minutes;

 static void Main(string[] args)
 {
   // Not sure about this line if it will run continuously every minute??
   System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(TimCallBack), null, 1000, 60000);

  Console.Read();
  timer.Dispose();
 }
   private static void TimCallBack(object o)
   {
      curMin = DateTime.Now.Minute;
      if (lastMinute < curMin)
      {
          // Do my work every minute
          lastMinute = curMin;
      }
    }

}

KISS - or are you competing for the Rube Goldberg award? ;-)

static void Main(string[] args)
{
   while(true)
   {
     DoSomething();
     if(Console.KeyAvailable)
     {
        break;     
     }
     System.Threading.Thread.Sleep(60000);
   }
}

I think your method should work assuming you don't press any keys on the console window. The answer above will definitely work but isn't the prettiest.

一旦main()退出,所有其他线程也将自动关闭。

If it needs to run the whole time, might it be a better solution to create a service? Example here .

Why not add your application to the Windows Task scheduler and do just one "task" per startup of your console app (and don't bother thinking about scheduling yourself?)

And to answer your question: No your sample doesn't "Loop", it's event driven and will close on key press.

Using an event which times out for the stop might work, something like this:

class Program
{
    static TimeSpan _timeSpan = new TimeSpan(0, 0, 5);
    static ManualResetEvent _stop = new ManualResetEvent(false);

    static void Main(string[] args)
    {
        Console.TreatControlCAsInput = false;
        Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e)
        { 
            _stop.Set();
            e.Cancel = true;
        };

        while (!_stop.WaitOne(_timeSpan))
        {
            Console.WriteLine("Waiting...");
        }
        Console.WriteLine("Done.");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM