释放 StreamReader 文件一秒钟
我有一个streamReader,我用它来持续监视文件中添加的任何新行, 它是这样的:
while (true)
{
try
{
line = sr.ReadLine();
if (line == null)
{
break;
}
if (!string.IsNullOrWhiteSpace(line))
{
//Do Stuff
}
Thread.Sleep(2);
}
}
现在我想时不时地释放该文件一段时间,
我可以关闭 sr 一两秒,然后重新使用它并再次使用它,但我想知道是否有适当的方法可以做到这一点..
i have a streamReader which i use to keep watching a file for any new lines added,
it goes like this :
while (true)
{
try
{
line = sr.ReadLine();
if (line == null)
{
break;
}
if (!string.IsNullOrWhiteSpace(line))
{
//Do Stuff
}
Thread.Sleep(2);
}
}
now i want to release the file for a while every now and then ,
i can close sr for a sec or two and then reintilize it and use it again but i was wondering if there is a proper way for doing that..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
FileSystemWatcher
进行跟踪更改文件,然后才打开文件以检查新行。您可以使用最后一个
seek
位置来开始新的搜索,因此不需要重新读取整个文件。Use
FileSystemWatcher
to track changes to the file and only then open the file to check for the new lines.You can use the last
seek
position to start the new seek from, so the whole file doesn't need to be re-read.重新打开,Seek()到原来的位置并继续工作应该是你最好的选择。如果您希望其他方能够继续访问该文件,只需指定适当的标志FileShare 例如 FileShare.ReadWrite
也许看看 .NET 4.0 的内存映射文件
Reopening, Seek() to the old position and continue work should be your best option. If you want other parties to be able to continue accessing the file, just specify proper flags for FileShare e.g. FileShare.ReadWrite
Perhaps look at memory mapped files for .NET 4.0