我编写了一些代码,将FileSystemWatcher
'Changed
事件转换为可观察的序列。
我的目标是将所有文件系统更改拆分为单独的流并限制它们。
例如,如果我有 10 个不同的文件,它们在半秒内更改了 3 次,那么每个文件我只会收到一次通知。
我担心的是GroupBy()
运营商。为此,(我假设)它需要随着时间的推移不断建立组并消耗少量内存。
这会导致“泄漏”吗?如果是,我该如何预防?
FileSystemWatcher _watcher = new FileSystemWatcher("d:\\") {
EnableRaisingEvents = true,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size
};
void Main()
{
var fileSystemEventStream =
Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>
(
_ => _watcher.Changed += _,
_ => _watcher.Changed -= _
)
.ObserveOn(ThreadPoolScheduler.Instance)
.SubscribeOn(ThreadPoolScheduler.Instance)
.GroupBy(ep => ep.EventArgs.FullPath, ep => ep.EventArgs.FullPath)
;
var res =
from fileGroup in fileSystemEventStream
from file in fileGroup.Throttle(TimeSpan.FromSeconds(1))
select file;
res.Subscribe(
ReceiveFsFullPath,
exception => {
Console.WriteLine ("Something went wrong - " + exception.Message + " " + exception.StackTrace);
});
Console.Read();
}
void ReceiveFsFullPath(string s){
Console.WriteLine ("Received file system event on thread " + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(s);
}