简体   繁体   中英

stream reliability

I came across a few posts that where claming that streams are not a reliable data structure, meaning that read/write operations might not follow through in all cases.

So:

a) Is there any truth to this consensus?

b) If so what are the cases in wich read/write operaitions might fail?

This consensus on streams which I came across claims that you sould loop through read/write operations until complete:

var bytesRead = 0;
var _packet = new byte[8192];    
while ((bytesRead += file_reader.Read(_packet, bytesRead, _packet.Length - bytesRead)) < _packet.Length) ;

Well, it depends on what operation you're talking about, and on what layer you consider it a failure.

For instance, if you attempt to read past the end of a stream (ie. read 1000 bytes from a file that only contains 100 bytes, or read a 1000 bytes from a position that is closer to the end of the file than 1000), you will get fewer bytes left. The stream read methods returns the number of bytes they actually managed to read, so you should check that value.

As for write operations, writing to a file might fail if the disk is full, or other similar problems, but in case of write operations you'll get back an exception.

If you're writing to sockets or other network streams, there is no guarantee that even if the Write method returns without exceptions, that the other end is able to receive it, there's a ton of problems that can go wrong along the way.

However, to alleviate your concerns, streams by themselves are not unreliable.

The medium they talk to, however, can be.

If you follow the documentation, catch and act accordingly when errors occur, I think you'll find streams are pretty much bullet-proof. There's a significant amount of code that has invested in this reliability.

Can we see links to those who claim otherwise? Either you've misunderstood, or they are incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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