阅读从C#中越来越多的文件? [英] Read from a growing file in C#?

查看:142
本文介绍了阅读从C#中越来越多的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#/。NET(在Windows上)有没有一种方法来读取使用文件流的成长的文件?当文件流被打开,但该文件将被另一个线程正在写入到文件的长度将是非常小的。如果/当FILESTREAM追上到其他线程(即当阅读()返回0字节读),我想停下来让文件缓冲了一下,然后继续阅读。

In C#/.NET (on Windows) is there a way to read a "growing" file using a file stream? The length of the file will be very small when the filestream is opened, but the file will be being written to by another thread. If/when the filestream "catches up" to the other thread (i.e. when Read() returns 0 bytes read), I want to pause to allow the file to buffer a bit, then continue reading.

我真的不希望使用 FileSystemWatcher的并保持创造新的文件流(如建议为日志文件),因为这不是一个日志文件(这是一个视频文件是连接上飞codeD)和性能是一个问题。

I don't really want to use a FilesystemWatcher and keep creating new file streams (as was suggested for log files), since this isn't a log file (it's a video file being encoded on the fly) and performance is an issue.

谢谢,
罗伯特·

Thanks,
Robert

推荐答案

您可以这样做,但你需要仔细跟踪读取该文件,并用写的位置 Stream.Seek 和线程之间适当的同步。通常情况下,你会使用的EventWaitHandle 或其子类的做数据同步,而且你还需要考虑的访问的FileStream <同步/ code>对象本身(可能通过锁定语句)。

You can do this, but you need to keep careful track of the file read and write positions using Stream.Seek and with appropriate synchronization between the threads. Typically you would use an EventWaitHandle or subclass thereof to do the synchronization for data, and you would also need to consider synchronization for the access to the FileStream object itself (probably via a lock statement).

更新:在回答这个问题我实现了类似的东西 - 的情况下一个文件正在后台下载和也被上传在同一时间。我使用的内存缓冲区,并张贴了要点已经工作code。 (这是GPL的,但可能并不重要你 - 。在任何情况下,你可以使用的原则,做自己的事)

Update: In answering this question I implemented something similar - a situation where a file was being downloaded in the background and also being uploaded at the same time. I used memory buffers, and posted a gist which has working code. (It's GPL but that might not matter for you - in any case you can use the principles to do your own thing.)

这篇关于阅读从C#中越来越多的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆