Reputation: 2242
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?
Upvotes: 3
Views: 2718
Reputation: 18096
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).
Upvotes: 3
Reputation: 65116
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.
Upvotes: 6