Created
May 3, 2021 16:17
-
-
Save emoacht/4122061c6eff2946527bf24edf5f75e7 to your computer and use it in GitHub Desktop.
Read text file with progress reporting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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