2012-12-25 24 views
0

我建立一個監聽使用FileSystemWatcher到文件夾,並創建一個新的文件時,將啓動一個定時器幾秒鐘,以確保整個文件夾中的應用程序。然後,啓動事件到我的主要UI線程運行將此文件添加到我的ListView。FileSystemWatcher的射擊新的文件我的事件,但我的UI更新兩次

成功創建新的文件添加到我的ListView但我的問題是添加後的第一個,第二個是加兩次,下一個文件中添加4倍等等

我的聽衆類:

public class FileListener 
{ 
    private static string _fileToAdd; 
    public event EventHandler _newFileEventHandler; 
    private static System.Timers.Timer _timer; 

    public void startListener(string directoryPath) 
    { 
     FileSystemWatcher watcher = new FileSystemWatcher(directoryPath); 
     _timer = new System.Timers.Timer(5000); 
     watcher.Filter = "*.pcap"; 
     watcher.Created += watcher_Created; 
     watcher.EnableRaisingEvents = true; 
     watcher.IncludeSubdirectories = true; 
    } 

    void watcher_Created(object sender, FileSystemEventArgs e) 
    {    
     _timer.Elapsed += new ElapsedEventHandler(myEvent); 
     _timer.Enabled = true; 
     _fileToAdd = e.FullPath; 
    } 

    private void myEvent(object sender, ElapsedEventArgs e) 
    { 
     _newFileEventHandler(_fileToAdd, EventArgs.Empty); 
     _timer.Stop(); 
    } 
} 

我的事件誰與新的文件句柄:

void listener_newFileEventHandler(object sender, EventArgs e) 
{ 
    string file = sender as string; 
    addFileToListFiew(file); 

} 

和功能將文件添加到我ListView

public void addFileToListFiew(string file) 
{ 
    this.Invoke((MethodInvoker)delegate 
    { 
     lvFiles.Items.Add(new ListViewItem(new string[] 
     { 
      file, "Waiting" 
     })); 
    }); 
} 
+0

您不斷添加事件處理程序的計時器。只添加一次myEvent處理程序。 –

+0

我加入_timer.Elapsed - =新ElapsedEventHandler(myEvent)_timer.Stop(後),它似乎是現在的工作很好,但是當我移動到我的文件夾中的幾個文件的同時,他們中的一個文件中多次出現 – user1269592

+0

有這裏有很好的答案,但你需要注意一件事 - 雙人事件。你需要警惕這種情況。看看這裏的細節部分:http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx –

回答

0
//You can unsubscribe from the previous event subscription using the following: 
//You may also need a global boolean variable to keep track of whether or not the watcher currently exists... Although, I am not sure if that is the best resolution for the problem... 
watcher.Created -= watcher_Created; 

//... 

if(eventSubscriptionExists) 
{ 
    //if already subscribed, either do nothing, or re-subscribe 

    //unsubscribe from event 
    watcher.Created -= watcher_Created; 
    //subscribe to event 
    watcher.Created += watcher_Created; 
} 
else 
{ 
    //if not already subscribed to event, start listening for it... 
    watcher.Created += watcher_Created; 
} 
+0

我應該在哪裏放watcher.Created - = watcher_Created? – user1269592

+0

我會將上面的邏輯添加到FileListener類中,並調用main函數來獲取布爾變量 –

+0

的值,我應該在哪裏放置if - else語句? – user1269592

相關問題