我写了一个简单的示例程序,它应该将数据写入文件,并在有数据时实时读取。我写了这段代码:
using System;
using System.IO;
using System.Reflection;
using System.Threading;
namespace Sample
{
class Program
{
static void Main(string[] args)
{
const string file = "sample.txt";
var thread = new Thread(() =>
{
var r = new Random();
using (var sw = new StreamWriter(new FileStream(file, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) {AutoFlush = true})
{
while (true)
{
Thread.Sleep(r.Next(100, 500));
sw.WriteLine(DateTime.Now);
}
}
});
thread.Start();
using (var watcher = new FileSystemWatcher
{
Path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
Filter = file,
NotifyFilter = NotifyFilters.LastWrite
})
{
var mse = new ManualResetEventSlim(false);
watcher.Changed += (sender, eventArgs) =>
mse.Set();
watcher.EnableRaisingEvents = true;
using (var sr = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)))
{
while (true)
{
mse.Wait();
ProcessData(sr.ReadToEnd());
mse.Reset();
}
}
}
}
private static void ProcessData(string s)
{
Console.WriteLine(s);
}
}
}但是似乎只有当文件打开时,watcher才能工作,但当它填充了信息(即使在StreamWriter上启用了AutoFlush标志)时就不起作用了。数据物理上在磁盘上,但watcher不会引发事件File changed。
我只想避免无限循环,只在写入时才处理数据。
发布于 2016-02-25 18:39:48
如果您不关闭它们,我认为您应该通过将FileStream和StreamWriter放在using子句中来处理它们:
string file = "sample.txt";
using (var fs =new FileStream(file, FileMode.Create,
FileAccess.ReadWrite, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs) {AutoFlush = true})
{
..
..
}在直接关闭或通过释放之前,不会通知文件系统已完成更改。否则,您将被已更改的事件淹没。
https://stackoverflow.com/questions/35623036
复制相似问题