Stream.Position 在调用 StreamReader.ReadLineAsync 后没有改变

Stream.Position doesn't change after call to StreamReader.ReadLineAsync

当我创建尝试读取这样的行时,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 等)。缓冲 使事情变得混乱。