gpt4 book ai didi

async-await - 为什么 ReadAsync 在 FileStream 中比在 C# 中的 StreamReader 更快?

转载 作者:行者123 更新时间:2023-12-01 10:49:00 24 4
gpt4 key购买 nike

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

ReadStreamReaderAsync

等待前的线程 ID:9

等待后的线程 ID:13

时间:76626

总字节数:687184052

读取文件流异步

等待前的线程 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;
}

最佳答案

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

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

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

关于async-await - 为什么 ReadAsync 在 FileStream 中比在 C# 中的 StreamReader 更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22790536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com