C# FileSystemWatcher 并发
2021-04-11 23:28
标签:hand dir als monit eset art ted and bool using System; namespace Demo public FileListen(string listenPath) private void Init() autoResetEvent = new AutoResetEvent(false); Thread thread = new Thread(DoWork); Reload(); private void Reload() private void DoWork() private void MonitorFileCreate(object sender, FileSystemEventArgs e) C# FileSystemWatcher 并发 标签:hand dir als monit eset art ted and bool 原文地址:https://www.cnblogs.com/zeshao/p/9019925.html
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
{
public class FileListen
{
private AutoResetEvent autoResetEvent;
private string listenPath = @"D:\项目资料\随笔\Demo\listen";
private Queue fileQueue = new Queue();
private static object objLock = new object();
private bool isWait = true;
{
this.listenPath = listenPath;
Init();
}
{
FileSystemWatcher watcher = new FileSystemWatcher(listenPath);
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.txt";
watcher.EnableRaisingEvents = true;
watcher.Created += new FileSystemEventHandler(MonitorFileCreate);
thread.Start();
}
{
DirectoryInfo dires = new DirectoryInfo(listenPath);
FileInfo[] files = dires.GetFiles().OrderBy(c => c.CreationTime).ToArray();
foreach (FileInfo file in files)
{
if (!fileQueue.Contains(file.FullName))
{
fileQueue.Enqueue(file.FullName);
//休眠1秒
Thread.Sleep(1000);
autoResetEvent.Set();
}
}
}
{
Console.WriteLine("DoWork Begin");
//等待信号
while (isWait)
{
autoResetEvent.WaitOne();
//锁定 防止并发
lock (objLock)
{
//获取文件队列信息 并移除
string path = fileQueue.Dequeue().ToString();
Console.WriteLine("正在处理=>" + path);
Console.WriteLine("处理中...");
Console.WriteLine("处理完成");
File.Delete(path);
}
}
}
{
if (e.ChangeType == WatcherChangeTypes.Created)
{
try
{
if (!fileQueue.Contains(e.FullPath))
{
Console.WriteLine("监听文件=>" + e.FullPath);
fileQueue.Enqueue(e.FullPath);
autoResetEvent.Set();
}
}
catch (Exception ex)
{
//LogHelper.Error(ex.Message + "\r\n" + ex.StackTrace);
}
}
}
}
}
文章标题:C# FileSystemWatcher 并发
文章链接:http://soscw.com/index.php/essay/74463.html