Skip to content

Instantly share code, notes, and snippets.

@emoacht
Created May 3, 2021 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emoacht/4122061c6eff2946527bf24edf5f75e7 to your computer and use it in GitHub Desktop.
Save emoacht/4122061c6eff2946527bf24edf5f75e7 to your computer and use it in GitHub Desktop.
Read text file with progress reporting
using System.Threading.Tasks;
public class TextReader
{
public double Percentage { get; set; }
public async Task ReadAsync(string filePath)
{
var progress = new Progress<(double current, double total)>();
progress.ProgressChanged += (_, e) => Percentage = e.current / e.total;
await ReadTextAsync(filePath, progress);
}
public static async Task<string> ReadTextAsync(string filePath, IProgress<(double current, double total)> progress)
{
using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using var reader = new StreamReader(stream);
var readTask = reader.ReadToEndAsync();
var progressTask = Task.Run(async () =>
{
while (stream.Position < stream.Length)
{
await Task.Delay(TimeSpan.FromMilliseconds(100));
progress.Report((stream.Position, stream.Length));
}
});
await Task.WhenAll(readTask, progressTask);
return readTask.Result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment