FileSystemWatcher在新文件上触发了我的事件,但我的UI更新了两次

本文关键字:我的 UI 更新 两次 事件 新文件 文件 FileSystemWatcher | 更新日期: 2023-09-27 17:49:26

我构建了一个应用程序,它使用FileSystemWatcher侦听文件夹,当创建新文件时,计时器启动几秒钟以确保整个文件都在文件夹中。然后开始事件到我的主ui线程运行添加这个文件到我的ListView。

成功创建的新文件被添加到我的ListView中,但我的问题是,在添加第一个文件后,第二个文件添加了两次,下一个文件添加了4次,等等…

my listener class:

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"
        }));
    });
}

FileSystemWatcher在新文件上触发了我的事件,但我的UI更新了两次

//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;
}