数据写入流时发生事件?
我正在尝试创建一个程序,一旦新数据写入 FileStream 对象,该程序就会调用一个操作。我当前的方法如下:
public class BlockingFileStream : FileStream
{
public override int Read(byte[] array, int offset, int count)
{
while (Position == Length) ;
return base.Read(array, offset, count);
}
public override int ReadByte()
{
while (Position == Length) ;
return base.ReadByte();
}
}
如您所见,此类所做的就是等待流的长度大于其当前位置。它似乎有效,但是,我一直想知道是否有更好的方法可以做到这一点。所以我的问题是:
是否有更好的方法来完成上面发布的代码片段中所做的事情?
I'm trying to create a program which invokes an action as soon as new data has been written to a FileStream object. My current approach is as follows:
public class BlockingFileStream : FileStream
{
public override int Read(byte[] array, int offset, int count)
{
while (Position == Length) ;
return base.Read(array, offset, count);
}
public override int ReadByte()
{
while (Position == Length) ;
return base.ReadByte();
}
}
As you can see, all this class does is wait until the stream's length is larger than its current position. It seems to be working, however, I've been wondering if there is any better way of doing this. So my question is:
Is there a better way of doing what is done in the code snipped posted above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能需要查看 FileSystemWatcher 以看看这对您来说是否是更好的解决方案。忙碌的等待通常不是一个好的解决方案。
You might want to take a look at the FileSystemWatcher to see if that would be a better solution for you. Busy waiting is usually not a good solution.
在这种情况下,我认为您不应该将文件保持在“打开”状态,因为另一个程序无法将数据写入该文件。
尝试使用
FileSystemWatcher
类 而不是接收有关文件更改的通知 (示例) 。In this case, I think you should not keep the file in "opened" state because another program could not write data to the file.
Try using the
FileSystemWatcher
class instead to receive notification about file changes (example).