I am writing a method to read large files using new ReadAsync methods. In my testing looks like FileStream ReadAsync is faster than StreamReader, not sure why?
ReadStreamReaderAsync
Thread ID Before Await : 9
Thread ID After Await : 13
Time : 76626
Total Bytes : 687184052
ReadFileStreamAsync
Thread ID Before Await : 9
Thread ID After Await : 10
Time : 19167
Total Bytes : 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;
}