为什么调用带有`count`参数为0的`StreamReader.ReadAsync`会使基础流的`Position`前进?

时间:2019-11-29 18:24:04

标签: c# .net streamreader defects

在使用.NET Framework的System.IO.StreamReader类时,我注意到我似乎奇怪的不一致行为:

调用Read(Char[], Int32, Int32)方法并为0参数传递count(即读取零字节),基础Position对象上的Stream属性是0,如预期。

但是,以相同的方式调用ReadAsync(Char[], Int32, Int32)方法时,底层Position对象上的Stream属性并不为零,正如我所期望的那样,而是内容的长度。流;我希望它在同步测试用例中为零。

这是框架实现中的错误还是我缺少一些东西?

以下测试代码演示:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Threading.Tasks;

namespace ExplorationTesting
{

    [TestClass]
    public class TestStreamReader
    {

        public static Stream CreateStream(string fromString)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.Write(fromString);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }

        [TestMethod] // Test Passes
        public void TestReadingZeroBytesFromStreamReader_StreamPositionIsZero()
        {
            using (Stream stream = CreateStream("Foo"))
            using (StreamReader reader = new StreamReader(stream)) {
                Assert.AreEqual(0, stream.Position);
                char[] buffer = new char[] { };
                var r = reader.Read(buffer, 0, 0);
                Assert.AreEqual(0, r);
                Assert.AreEqual(0, stream.Position);
            }
        }

        [TestMethod] // Test Fails
        public async Task TestReadingZeroBytesFromStreamReader_StreamPositionIsZero_Async()
        {

            using (Stream stream = CreateStream("Foo"))
            using (StreamReader reader = new StreamReader(stream)) {
                Assert.AreEqual(0, stream.Position);
                char[] buffer = new char[] { };
                var r = await reader.ReadAsync(buffer, 0, 0);
                Assert.AreEqual(0, r);
                Assert.AreEqual(0, stream.Position); // Assert.AreEqual failed. Expected:<0>. Actual:<3>. 
            }
        }
    }
}

0 个答案:

没有答案