Is this loop cycle endless?

I have the following code: is this running an infinite loop? I try 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; } } } 
+4
source share
6 answers

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); } } 
+10
source

I think your method should work if you do not press any keys in the console window. The answer above will definitely work, but not the most beautiful.

+2
source

Once your main() completes, all other threads will also be automatically closed.

+1
source

If you need it to run all the time, maybe this is the best solution to create a service? An example is here .

+1
source

Why not add the application to the Windows Task Scheduler and complete only one task when starting the console application (and don't think about scheduling yourself?)

And to answer your question: not a single sample is "Loop", its action does not work and will close when you press a key.

+1
source

Using an event whose execution time can be stopped can look 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."); } } 
-1
source

Source: https://habr.com/ru/post/1302144/


All Articles