C# StreamReader.Read 和 StreamReader.ReadBlock 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/592244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:31:15  来源:igfitidea点击:

Difference between StreamReader.Read and StreamReader.ReadBlock

c#iostreamreader

提问by J M

The documentation simply says ReadBlock is

该文档只是说 ReadBlock 是

"a blocking version of Read"

“阅读的阻塞版本”

but what does that mean?

但是,这是什么意思?

Someone else has asked the question before but, huh?

之前有人问过这个问题,但是,嗯?

http://www.pcreview.co.uk/forums/thread-1385785.php

http://www.pcreview.co.uk/forums/thread-1385785.php

The guy answering said

回答的人说

Basically, it means that you can rely on StreamReader.ReadBlock not returning until either it's read as much as you've asked it to, or it's reached the end of the stream.

基本上,这意味着您可以依赖 StreamReader.ReadBlock 不会返回,直到它按照您的要求被读取,或者到达流的末尾。

Am I understanding correctly that this is required because Read may not give you everything you asked for? And that just because it returns 0 does NOT mean you reached the end of the file?

我是否正确理解这是必需的,因为 Read 可能无法为您提供所需的一切?仅仅因为它返回 0 并不意味着你到达了文件的末尾?

So this means check something other than the number of bytes returned (EndOfStream?) or use ReadBlock instead?

所以这意味着检查返回的字节数(EndOfStream?)以外的其他内容还是使用 ReadBlock?

采纳答案by David

ReadBlock does not mean it is thread safe. If you use Reflector to look at the implementation of StreamReader.ReadBlock (which is inherited from TextReader.ReadBlock), all it does is make multiple calls to the "Read" method until either the "Read" method returns 0 or we have read as many bytes as requested. This is needed because the "Read" method will not necessarily return as many bytes as you asked for.

ReadBlock 并不意味着它是线程安全的。如果您使用 Reflector 查看 StreamReader.ReadBlock(继承自 TextReader.ReadBlock)的实现,它所做的就是多次调用“Read”方法,直到“Read”方法返回 0 或我们已读取为请求的许多字节。这是必需的,因为“读取”方法不一定会返回与您要求的一样多的字节。