从FileSystemWatcher C#中捕获的事件丢失

时间:2012-09-05 08:56:16

标签: c# events

我正在尝试创建一个简单的应用程序,将所有文件写入某个目录移动到其他目录。这是我的问题:如果我在我的目录中一次写入10000个以外的文件(超过1KB的小.txt文件) - 其中一些不处理移动输出目录。我正在使用FileSystemWatcher事件处理程序来解决这个问题。这是我的代码示例:

Class MyProgramm
{
    void Process(Object o, FileSystemEventArgs e)
    {
        //do something with e.Name file
    }
    void main()
    {
        var FSW = New FileSystemWatcher{Path = "C:\\InputDir"};
        FSW.Created += Process;
        FSW.EnableRisingEvents = true;
        Thread.Sleep(Timeout.Infinite);
    }
}

最后,我们处理了一些文件,但是一些写入的文件仍未处理。 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我遇到了与FileSystemWatcher类似的问题。它似乎经常“丢球”。我通过扩展“ServiceBase”寻求替代解决方案,自从它作为Windows服务上线以来一直在不断地工作。希望这会有所帮助:

    public partial class FileMonitor : ServiceBase
    {
        private Timer timer;
        private long interval;
        private const string ACCEPTED_FILE_TYPE = "*.csv";

        public FileMonitor()
        {           
            this.ServiceName = "Service";
            this.CanStop = true;
            this.CanPauseAndContinue = true;
            this.AutoLog = true;
            this.interval = long.Parse(1000);
        }

        public static void Main()
        {
            ServiceBase.Run(new FileMonitor());
        }

        protected override void OnStop()
        {
            base.OnStop();
            this.timer.Dispose();
        }

        protected override void OnStart(string[] args)
        {
            AutoResetEvent autoEvent = new AutoResetEvent(false);
            this.timer = new Timer(new TimerCallback(ProcessNewFiles), autoEvent, interval, Timeout.Infinite);
        }

        private void ProcessNewFiles(Object stateInfo)
        {
            DateTime start = DateTime.Now;
            DateTime complete = DateTime.Now;

            try
            {
                string directoryToMonitor = "c:\mydirectory";
                DirectoryInfo feedDir = new DirectoryInfo(directoryToMonitor);
                FileInfo[] feeds = feedDir.GetFiles(ACCEPTED_FILE_TYPE, SearchOption.TopDirectoryOnly);             

                foreach (FileInfo feed in feeds.OrderBy(m => m.LastWriteTime))
                {
                    // Do whatever you want to do with the file here
                }
            }
            finally
            {
                TimeSpan t = complete.Subtract(start);
                long calculatedInterval = interval - t.Milliseconds < 0 ? 0 : interval - t.Milliseconds;
                this.timer.Change(calculatedInterval, Timeout.Infinite);
            }
        }       
    }