简体   繁体   English

数据已写入流时发生的事件?

[英]Event when data has been written to stream?

I'm trying to create a program which invokes an action as soon as new data has been written to a FileStream object.我正在尝试创建一个程序,该程序在新数据写入 FileStream 对象后立即调用操作。 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?有没有更好的方法来做上面发布的代码片段中所做的事情?

You might want to take a look at the FileSystemWatcher to see if that would be a better solution for you.您可能想查看FileSystemWatcher ,看看这是否对您来说是一个更好的解决方案。 Busy waiting is usually not a good solution.忙着等待通常不是一个好的解决方案。

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 ).尝试使用FileSystemWatcher来接收有关文件更改的通知( 示例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM