Hooch
Hooch

Reputation: 29693

.NET Console application. Way to cancel infinite loop with long blocking operation

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?

Upvotes: 2

Views: 1365

Answers (1)

Agent_Spock
Agent_Spock

Reputation: 1197

Use a ManualResetEvent:

ManualResetEvent mre=new ManualResetEvent(false);
//......
var signalled=mre.WaitOne(TimeSpan.FromSeconds(8));
if(!signalled)
{
    //timeout occurred
}

elsewhere (before the 8 seconds is up):

mre.Set(); //unfreezes paused Thread and causes signalled==true

and allow the unblocked thread to terminate gracefully. Thread.Abort is evil and should be avoided.

Upvotes: 1

Related Questions