c# - 调用 StreamReader.ReadLineAsync 后 Stream.Position 不会更改

标签 c# .net asynchronous stream

当我尝试读取这样的行时,Stream.Position 在第一次调用 StreamReader.ReadLineAsync 后会更改一次,然后在多次调用后不会更改。

var stream = new FileStream(
filename,
FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 4096, useAsync: true);

using (var sr = new StreamReader(stream))
{
    while(stream.Position <= stream.Length)
    {
        var pos = stream.Position;
        var line = sr.ReadLineAsync().Result;
        Console.WriteLine("{0}: {1}", pos, line);
    }
}

当我运行这个时,给定输入

1 2 3
4 5 6
7 8 9
10 11 12

它给了我输出

0: 1 2 3
29: 4 5 6
29: 7 8 9
29: 10 11 12
29: 
29: 

等等。

最佳答案

StreamReader.ReadLine(以及等效的ReadLineAsync)通常会读取超过仅仅一行 - 它基本上读入缓冲区,然后解释该缓冲区。这比一次读取一个字节要高效得多,但这确实意味着流将比严格意义上需要的进一步前进。

基本上,我不会尝试将 Stream.Position 用于由另一个对象包装的流(例如 BufferedStreamStreamReader ETC)。缓冲会让让事情变得困惑。

关于c# - 调用 StreamReader.ReadLineAsync 后 Stream.Position 不会更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28656630/

相关文章:

c# - yield return返回什么样的类

c# - 最佳实践 boolean 逻辑倍数不等于

.net - 使用带有数组参数的 Thread.VolatileWrite()

c# - 读取文件时出现 UnauthorizedAccessException

c# - 搜索单个结果时与 Entity Framework 一起使用的集合

c# - DataGridView 单元格编辑结束事件

.net - 错误 "Could not load file"但我没有要求它

JavaScript 异步函数

c# - 如何使用 ContinueWith 处理任务取消?

c# - WPF 中的异步任务