为了处理大量的文件观察器事件,我在我的文件观察器中实现了以下代码。
我已将文件夹复制到监视位置该文件夹中有大约 40K 文件和文件夹。问题是队列项目没有立即得到处理。在一段时间内发生的处理。即文件夹复制大约需要 40 分钟。但处理队列从文件复制开始大约需要 4-5 小时
我希望在复制文件夹后立即处理这些事件。
这是我的 FileProcessor 类:
class FileProcessor
{
private Queue<string> workQueue;
private Thread workerThread;
private EventWaitHandle waitHandle;
public FileProcessor()
{
workQueue = new Queue<string>();
waitHandle = new AutoResetEvent(true);
}
public void QueueInput(string filepath)
{
workQueue.Enqueue(filepath);
// Initialize and start thread when first file is added
if (workerThread == null)
{
workerThread = new Thread(new ThreadStart(Work));
workerThread.Start();
}
// If thread is waiting then start it
else if (workerThread.ThreadState == ThreadState.WaitSleepJoin)
{
waitHandle.Set();
}
}
private void Work()
{
while (true)
{
string filepath = RetrieveFile();
if (filepath != null)
ProcessFile(filepath);
else
waitHandle.WaitOne();
}
}
private string RetrieveFile()
{
if (workQueue.Count > 0)
return workQueue.Dequeue();
else
return null;
}
private void ProcessFile(string filepath)
{
// Some processing done on the file
}
}
每当引发 FileSystemWatcher.Created 事件时都会使用它:
FileProcessor fileprocessor = new FileProcessor()
void onCreated(object source, FileSystemEventArgs e)
{
try
{
fileprocessor.QueueInput(e.FullPath);
}
catch (Exception ex)
{
}
}