Good way to create idle loop in C #?

I have an application that installs FileSystemWatcher. It should work endlessly.

What is the best way to start it in standby mode?

I'm currently doing

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

which seems to work (i.e. captures events and does not use the kernel in a busy cycle).

Any idiom? Any problem with this approach?

+3
source share
5 answers

As I understood from your comment, you need your application to run endlessly, and this is a console application that has breakfast with another executable.

It is better to use Console.ReadLine instead of a loop. or use the Monitor.Wait method to endlessly block the stream

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

FileSystemWatcher.WaitForChanged - (). , , . . EnableRaisingEvents true. , , . . , .

, . . , . .

    Do
        Dim i As WaitForChangedResult = Me.FileSystemWatcher1.WaitForChanged(WatcherChangeTypes.All, 1000)
    Loop Until fCancel

[] ". EnableRaisingEvents true." Microsoft , FileSystemWatcher . :

    /// <internalonly/>
    /// <devdoc>
    /// </devdoc>
    [Browsable(false)] 
    public override ISite Site {
        get { 
            return base.Site; 
        }
        set { 
            base.Site = value;

            // set EnableRaisingEvents to true at design time so the user
            // doesn't have to manually. We can't do this in 
            // the constructor because in code it should
            // default to false. 
            if (Site != null && Site.DesignMode) 
                EnableRaisingEvents = true;
        } 
    }

[update] WaitForChanged EnableRaisingEvents System.Threading.Monitor.Wait.

+9

Thread.Sleep() , . , . . Console.ReadLine() , , .

, .

, , , , , .

+2
+2

... ? , ?

Windows , ?

, , , :

public class Foo
{
   private FileSystemWatcher _fs;

   private volatile bool _stopped = false;

   public Foo()
   {
       _fs = new FileSystemWatcher();
       ...
   }

   public void Start()
   {
       _stopped = false;
       Thread t = new Thread (new ThreadStart(DoWork));
       t.Start();
   }

   private void DoWork()
   {
       while( !_stopped )
       {
           Thread.Sleep(1);
       }
   }

   public void Stop()
   {
       _stopped = true;
   }

}
0

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


All Articles