none
替代 FileSystemWatcher 类 RRS feed

  • 问题

  • 您好:

    最近的学习中,发现一个FileSystemWatcher 类,但是消耗cpu太大了,有没有好点的办法,能达到FileSystemWatcher  相同的功能,同时使cpu使用变小。下面是我的主要代码

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public void Run()
        {
          // Create a new FileSystemWatcher and set its properties.
          FileSystemWatcher watcher1 = new FileSystemWatcher();
          FileSystemWatcher watcher2 = new FileSystemWatcher();
          //监视运行环境下的路径
          watcher1.Path = AppDomain.CurrentDomain.BaseDirectory;
          watcher2.Path = AppDomain.CurrentDomain.BaseDirectory;
          /* Watch for changes in LastAccess and LastWrite times, and
            the renaming of files or directories. */
          watcher1.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
            ;
          watcher2.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
            ;
          // Watching config and xml files.
          watcher1.Filter = "*.xml";
          watcher2.Filter = "*.config";
    
          // Add event handlers.
          watcher1.Changed += new FileSystemEventHandler(OnChanged);
          //watcher1.Created += new FileSystemEventHandler(OnChanged);
          //watcher1.Deleted += new FileSystemEventHandler(OnChanged);
          watcher2.Changed += new FileSystemEventHandler(OnChanged);
          //watcher2.Created += new FileSystemEventHandler(OnChanged);
          //watcher2.Deleted += new FileSystemEventHandler(OnChanged);
          // watcher.Renamed += new RenamedEventHandler(OnRenamed);
    
          // Begin watching.
          watcher1.EnableRaisingEvents = true;
          watcher2.EnableRaisingEvents = true;
          //begain wathching when the program is running
          while (true) ;
        
        }
    
        // Define the event handlers.
        private void OnChanged(object source, FileSystemEventArgs e)
        {
          // Specify what is done when a file is changed, created, or deleted.
          _ischanged = true;
          //Console.WriteLine(DateTime.Now.ToShortDateString());
        }

     

    同时,我会在console app中创建个线程去执行上面的语句,appreciate it
    2011年8月20日 1:56