[英]Use timer with fileSystemWatcher in C#
方案是我有一個根文件夾來監視任何新文件夾(包含文件)並設置一個計時器來單獨壓縮每個文件夾。 但是,在調用zip函數之前,我無法判斷文件夾中的文件是否是最后一個文件,因此,只要在壓縮文件夾之前創建了新文件,我就想將計時器重置為該文件夾。
我使用FileSystemWatcher
來監視根文件夾及其子文件夾。
下面是我嘗試過的代碼的一部分,源代碼可以在這里找到。 任何幫助將受到高度贊賞。
public class FileWatcher
{
private FileSystemWatcher _watcherRoot;
private Timer _timer;
private readonly string _watchedPath;
public FileWatcher(string path)
{
// _watcher = new FileSystemWatcher();
_timer = new Timer();
_watchedPath = path;
InitWatcher();
}
public void InitWatcher()
{
_watcherRoot = new FileSystemWatcher();
_watcherRoot.Path = _watchedPath;
_watcherRoot.IncludeSubdirectories = true;
_watcherRoot.EnableRaisingEvents = true;
_watcherRoot.Created += new FileSystemEventHandler(OnCreated);
}
private void OnCreated(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Created)
{
string fullPath = e.FullPath;
if (sender == _watcherRoot)
{
// If detect new folder, set the timer to 5 sec
_timer.Interval = 5000;
_timer.Elapsed += OnTimedEvent;
_timer.AutoReset = true;
_timer.Enabled = true;
// a directory
Console.WriteLine($"{fullPath.ToString()} created on {DateTime.Now}");
}
}
}
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
// Create a 2nd Watcher??
// Reset the timer in here??
}
這里有一個簡單的擴展方法來重置給定的計時器。
public static void Reset(this Timer timer)
{
timer.Stop();
timer.Start();
}
要從事件內部獲取計時器對象,您需要將sender
System.Timers.Timer()
為System.Timers.Timer()
或者只在靜態上下文中使用計時器。
有一個非常聰明的庫Reactive Extensions ,最初由Microsoft編寫為“Rx”,但現在放在“System.Reactive”命名空間中。 它允許您非常簡單地編寫復雜的事件驅動代碼。
例如,在您正在描述的場景中,您可以對FileSystemWatcher
的事件做出“反應”並使用Reactive“Throttle”,這意味着只有在一段時間之后才會收到事件的通知。事件沒有發生。 您還可以將多個不同的事件合並在一起。 將這兩個功能放在一起,並訂閱您的方法。
如果這聽起來像是一個可能的解決方案,你可能想看看Rx的Intro ,這里有一個與解決這個問題的方法有關的問題,包括在各種答案中做到這一點的4種方法: 包裝文件觀察器在反應式擴展中 (這不是該問題的重復,因為你問的是Timers,我建議你可能想要使用Reactive Extensions)。
我使用lambda表達式來解決這個問題,將計時器和觀察者“綁定”在一起,這就是我發現的類似於這篇文章的內容 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.