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?