I'm creating small applciaiton that will be used to detect some changes on system. It is used by admins so it doesn't have to nice and "perfect".
I have loop that checks for changes. I want to check for changes once every 10 seconds. But I would like to be able to "cancel" that thread.sleep with button press to get out of that loop.
static async void Main(string[] args) { Console.WriteLine("Logger started. Press any key to exit application.\n"); while (!Console.KeyAvailable) //Works. but only every 10 seconds { CheckForAndLogChanges(); Thread.Sleep(10000); } //Rest of code that I want to execute right after pressing key without waiting 10s. } Update: I like answer with timer.
This is what I also came up with:
static void Main(string[] args) { Console.WriteLine("Logger started. Press any key to exit application.\n"); var backgroutTask = new Task(WorkerThread, TaskCreationOptions.LongRunning); backgroutTask.Start(); Console.ReadKey(false); } static async void WorkerThread() { while (true) { CheckForAndLogChanges(); await Task.Delay(100); } } What is the adventage of using timer over this task?
Timercould be quite OK in such case. But there are different timers, see e.g. stackoverflow.com/q/1416803 (there are even more). There are different ways to synchronize with the main thread and different ways to wait for possible running operations to terminate. I have no time to extend the answer accordingly, and just did not want to keep it half way, since it might be misleading for someone.