开发者

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??
   Sy开发者_如何学Cstem.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.


As soon as your main() exits, all the other threads will be automatically closed, too.


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.");
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜