Search code examples
c#.netbusy-loop

Good way to create an idle loop in C#?


I have an app it sets up a FileSystemWatcher. It should run indefinitely.

What is the best way to have it run in an idle loop?

I'm currently doing

FileSystemWatcher watch = ... //setup the watcher
watch.EnableRaisingEvents = true;
while (true) 
{
    Thread.Sleep(int.MaxValue);
}

which seems to work (ie, captures the events and doesn't use up a core in a busy loop).

Any other idiom? Any problem with this approach?


Solution

  • As I understood from your comment you need your application to run indefinitely and it is a console app that is lunched by another executable.

    It is better to use Console.ReadLine instead of looping. or use Monitor.Wait method to block the thread indefinitely

    object sync = new object();
    lock(sync)
    Monitor.Wait(sync);