优势
- 异步处理:提高了文件变化处理的效率,避免了阻塞主线程。
- 线程安全:使用了线程安全的队列来避免多线程环境下的竞态条件。
- 日志记录:异步日志记录减少了对主线程的干扰,并且能够处理大量事件。
- 灵活配置:可以通过配置文件调整监控目录和过滤规则,增加了灵活性。
- 支持子目录:可以监控指定目录及其所有子目录中的文件变化。
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
// 定义一个类来封装文件变化的事件信息
public class FileChangeEvent
{
public string FilePath { get; set; }
public WatcherChangeTypes ChangeType { get; set; }
public DateTime ChangeTime { get; set; }
}
class Program
{
private static FileSystemWatcher _fileSystemWatcher; // 用于监控文件系统的对象
private static ConcurrentQueue<FileChangeEvent> _changeQueue = new ConcurrentQueue<FileChangeEvent>(); // 线程安全的队列,用于存储文件变化事件