Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fsmaiorano/2924e6bddb1ba838b52eb6e622f870a8 to your computer and use it in GitHub Desktop.
Save fsmaiorano/2924e6bddb1ba838b52eb6e622f870a8 to your computer and use it in GitHub Desktop.
Sample for using `IProgress` in long-running tasks in C#
/*
`IProgress<T>` in C# is an interface provided by the .NET Framework to report progress in an asynchronous operation. It allows a producer (usually a background task) to communicate progress updates to a consumer (often the UI thread or another monitoring task).
This setup ensures that the progress reporting mechanism is thread-safe and that the consumer of the progress updates can safely update the UI or other state based on the progress.
*/
// var progress = new Progress<(long count, List<string> files)>(ReportProgress);
var progress = new Progress<(long count, List<string> files)>();
progress.ProgressChanged += (_, data) => {
Console.WriteLine($"{data.count} files read. Last file: {data.files.Last()}");
};
await ReadFiles(progress);
return;
static async Task ReadFiles(IProgress<(long count, List<string> files)>? progress) {
var files = new List<string>();
for (var i = 1; i < 1000; i++) {
await Task.Delay(500);
files.Add($"File {i}");
progress?.Report((i, files));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment