当前位置: 首页 > news >正文

C#高效异步文件监控与日志记录工具

优势

  1. 异步处理:提高了文件变化处理的效率,避免了阻塞主线程。
  2. 线程安全:使用了线程安全的队列来避免多线程环境下的竞态条件。
  3. 日志记录:异步日志记录减少了对主线程的干扰,并且能够处理大量事件。
  4. 灵活配置:可以通过配置文件调整监控目录和过滤规则,增加了灵活性。
  5. 支持子目录:可以监控指定目录及其所有子目录中的文件变化。
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>(); // 线程安全的队列,用于存储文件变化事件private static CancellationTokenSource _cts = new CancellationTokenSource(); // 用于取消异步任务的令牌源private static string _logFilePath = "file_changes.log"; // 记录日志的文件路径static async Task Main(string[] args){// 从配置文件读取监控目录和过滤规则string directoryToWatch = GetConfigValue("DirectoryToWatch", @"C:\Path\To\Directory");string filter = GetConfigValue("Filter", "*.*");// 创建FileSystemWatcher实例并配置_fileSystemWatcher = new FileSystemWatcher(directoryToWatch){NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,Filter = filter,IncludeSubdirectories = true};// 订阅事件_fileSystemWatcher.Created += OnChanged;_fileSystemWatcher.Changed += OnChanged;_fileSystemWatcher.Deleted += OnChanged;_fileSystemWatcher.Renamed += OnRenamed;// 开始监视_fileSystemWatcher.EnableRaisingEvents = true;// 启动异步任务来处理文件变化事件Task processingTask = Task.Run(() => ProcessFileChanges(_cts.Token));Console.WriteLine($"Monitoring changes to: {directoryToWatch}");Console.WriteLine("Press 'q' to quit the sample.");// 等待用户输入以结束程序while (Console.Read() != 'q') ;// 取消处理任务并等待完成_cts.Cancel();await processingTask;}private static void OnChanged(object source, FileSystemEventArgs e){// 将文件变化事件添加到队列_changeQueue.Enqueue(new FileChangeEvent{FilePath = e.FullPath,ChangeType = e.ChangeType,ChangeTime = DateTime.Now});}private static void OnRenamed(object source, RenamedEventArgs e){// 将重命名事件添加到队列_changeQueue.Enqueue(new FileChangeEvent{FilePath = e.FullPath,ChangeType = WatcherChangeTypes.Renamed,ChangeTime = DateTime.Now});}private static async Task ProcessFileChanges(CancellationToken token){// 持续处理队列中的文件变化事件while (!token.IsCancellationRequested){if (_changeQueue.TryDequeue(out FileChangeEvent changeEvent)){// 处理并记录文件变化事件到日志await LogChangeEventAsync(changeEvent);}else{// 如果队列为空,稍作等待以减少CPU使用率await Task.Delay(100, token);}}}private static async Task LogChangeEventAsync(FileChangeEvent changeEvent){// 异步记录文件变化事件到日志文件string logMessage = $"{changeEvent.ChangeTime}: {changeEvent.FilePath} - {changeEvent.ChangeType}";await File.AppendAllTextAsync(_logFilePath, logMessage + Environment.NewLine);}private static string GetConfigValue(string key, string defaultValue){// 从配置文件或环境变量读取配置值// 这里简单地返回默认值,实际应用中可以读取真实的配置return defaultValue;}
}


http://www.mrgr.cn/news/7644.html

相关文章:

  • node npm nvm 地址
  • 【Qt】输入类控件QDail
  • Python算法工程师面试整理-数据结构
  • 【数据结构】链表
  • 使用React和AntDesign构建初始前端项目及路由配置
  • vscode修改选中文字颜色及当前tab颜色
  • 红黑树
  • C++动态规划及九种背包问题
  • ESP RainMaker OTA 自动签名功能的安全启动
  • 井盖异动传感器:为城市安全加码
  • MATLAB 手动实现点云投影滤波器 (76)
  • 51单片机
  • 【赵渝强老师】管理MySQL的用户
  • 电子电气架构--- 智能汽车电子架构的核心诉求
  • 嵌入式day32
  • Linux:Bash中的命令介绍(简单命令、管道以及命令列表)
  • 【Docker深入浅出】【四】单体应用容器化与Dockerfile怎么写
  • 【精选】推荐7款AI论文一键生成论文、开题报告和文献综述网站
  • 鹏城杯 2022 取证writeup
  • 秋招力扣Hot100刷题总结——双指针