为什么ReadAsync在FileStream和C#中的StreamReader中更快?

时间:2014-04-01 15:39:17

标签: async-await

我正在编写一种使用新的ReadAsync方法读取大文件的方法。在我的测试中看起来像FileStream ReadAsync比StreamReader更快,不知道为什么?

ReadStreamReaderAsync

等待之前的线程ID:9

等待后的线程ID:13

时间:76626

总字节数:687184052

ReadFileStreamAsync

等待之前的线程ID:9

等待后的线程ID:10

时间:19167

总字节数:687184052

  static async Task<long> ReadStreamReaderAsync(string filename)
    {
        Console.WriteLine("Thread ID Before Await : {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
        long totalBytes = 0;
        var sp = new Stopwatch();
        sp.Start();
        using (StreamReader reader = new StreamReader(filename, Encoding.Default))
        {
            char[] buffer = new char[0x1000];
            int numRead;
            while ((numRead = await reader.ReadAsync(buffer, 0, buffer.Length)) != 0)
            {
                totalBytes += numRead;
            }
        }

        sp.Stop();
        Console.WriteLine("Thread ID After Await : {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("Time : {0}", sp.ElapsedMilliseconds);
        return totalBytes;
    }

    static async Task<long> ReadFileStreamAsync(string filePath)
    {
        Console.WriteLine("Thread ID Before Await : {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
        long totalBytes = 0;
        var sp = new Stopwatch();
        sp.Start();
        using (FileStream sourceStream = new FileStream(filePath,
            FileMode.Open, FileAccess.Read, FileShare.Read,
            bufferSize: 4096, useAsync: true))
        {
            byte[] buffer = new byte[0x1000];
            int numRead;
            while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
            {
                totalBytes += numRead;
            }          
        }

        sp.Stop();
        Console.WriteLine("Thread ID After Await : {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("Time : {0}", sp.ElapsedMilliseconds);
        return totalBytes;
    }

1 个答案:

答案 0 :(得分:6)

StreamReader正在使用编码器读取数据(UTF-8)。

如果你使用过基于UTF-8的文件,你可能会收到较少的数据,因为UTF-8可以编码为很多字节,编码器会理解这一点。

FileStream愚蠢,正在为您提供原始数据并相信您知道如何处理它。因此,如果您正在阅读文本文件,则应使用StreamReader(使用正确的编码器)