gpt4 book ai didi

c# - 将一系列事件转换为更细粒度的值序列

转载 作者:行者123 更新时间:2023-11-30 17:56:20 25 4
gpt4 key购买 nike

简而言之,我正在尝试使用 Reactive Library 来实现一个简单的 tail 实用程序,以在新行附加到文件时主动监视它们。这是我到目前为止得到的:

    static void Main(string[] args)
{
var filePath = @"C:\Users\wbrian\Documents\";
var fileName = "TestFile.txt";
var fullFilePath = filePath + fileName;
var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var sr = new StreamReader(fs, true);
sr.ReadToEnd();
var lastPos = fs.Position;

var watcher = new FileSystemWatcher(filePath, fileName);
watcher.NotifyFilter = NotifyFilters.Size;
watcher.EnableRaisingEvents = true;

Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
action => watcher.Changed += action,
action => watcher.Changed -= action)
.Throttle(TimeSpan.FromSeconds(1))
.Select(e =>
{
var curSize = new FileInfo(fullFilePath).Length;
if (curSize < lastPos)
{
//we assume the file has been cleared,
//reset the position of the stream to the beginning.
fs.Seek(0, SeekOrigin.Begin);
}
var lines = new List<string>();
string line;
while((line = sr.ReadLine()) != null)
{
if(!string.IsNullOrWhiteSpace(line))
{
lines.Add(line);
}
}
lastPos = fs.Position;
return lines;
}).Subscribe(Observer.Create<List<string>>(lines =>
{
foreach (var line in lines)
{
Console.WriteLine("new line = {0}", line);
}
}));

Console.ReadLine();
sr.Close();
fs.Close();
}

如您所见,我从 FileWatcher 事件创建了一个 Observable,该事件在文件大小更改时触发。从那里,我确定哪些行是新行,可观察对象返回一个新行列表。理想情况下,可观察序列只是一个代表每个新行的字符串。 observable 返回 List 的唯一原因是因为我根本不知道如何处理它。任何帮助将不胜感激。

最佳答案

您可以使用 SelectMany :

SelectMany(lines => lines)
.Subscribe(Observer.Create<string>(line => { Console.WriteLine("new line = {0}", line); });

关于c# - 将一系列事件转换为更细粒度的值序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14268511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com