使用文件系統觀察程序觀察目錄並處理新文件時創建的文件。我使用帶後臺工作的定時器來防止併發問題和內存溢出。在使用文件系統觀察程序時處理文件不止一次
這是我
//creating the watcher
watcher = new FileSystemWatcher();
watcher.Path = @"C:\Users\me\Desktop\watch";
watcher.Filter = "*.*";
watcher.Created += new FileSystemEventHandler(copied);
watcher.EnableRaisingEvents = true;
//hooking to creation event
void copied(object sender, FileSystemEventArgs e)
{
if (bwork.IsBusy == false)
{
bworkprocesslist.Add(e.FullPath);
}
else
{
bworkpendinglist.Add(e.FullPath);
}
}
//used timer to prevent concurrent access of resources and memory overflow
private void timer1_Tick(object sender, EventArgs e)
{
if (bwork.IsBusy==false)
{
bwork.RunWorkerAsync();
}
}
// Maintaining Lists and removed processed file from the main list
private void bwork_DoWork(object sender, DoWorkEventArgs e)
{
List<string> removedfiles = new List<string>();
foreach (string pfile in bworkprocesslist)
{
process(pfile) //Do processing of pfile
removedfiles.Add(pfile);
}
foreach (string x in removedfiles)
{
bworkprocesslist.Remove(x);
}
}
//Add files from pending list after background worker completion
void bwork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
foreach (string s in bworkpendinglist)
{
bworkprocesslist.Add(s);
bworkpendinglist.Remove(s);
}
}
代碼工作沒有任何問題。但有時候處理一個文件超過once.I當錯誤發生時想不通。
那麼你是否打算在我的程序中扔掉這個功能? – techno
這取決於你的程序。 :)如果蒼蠅監測是核心功能 - 那麼顯然你不能把它扔掉。但是因爲這個事件可以多次提交一個文件 - 你必須以某種方式處理它。可能你必須檢查這個文件是否已經加入到處理列表中,或者檢查是否已經處理過或者類似的東西。在應用程序上下文之外很難提出更多建議。 –
它不是核心功能,但其功能之一。即使文件被處理兩次也沒有損害,因爲它會被替換。但爲了防止浪費的資源和CPU週期,我會檢查文件是否已被添加到清單:) – techno