简体   繁体   English

流可靠性

[英]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? a)这个共识有什么道理吗?

b) If so what are the cases in wich read/write operaitions might fail? b)如果是,那么读/写操作中的哪些情况可能会失败?

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. 例如,如果您尝试读取流的末尾(即,从仅包含100个字节的文件中读取1000个字节,或者从比文件末尾更近的位置(而不是1000个位置)中读取1000个字节),您将剩下更少的字节。 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. 如果您正在写套接字或其他网络流,则不能保证即使Write方法无例外地返回,另一端也可以接收它,在此过程中可能会出现很多问题。

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. 您可能误会了,或者它们不正确。

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

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