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?
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.