-
-
Save fsmaiorano/2924e6bddb1ba838b52eb6e622f870a8 to your computer and use it in GitHub Desktop.
Sample for using `IProgress` in long-running tasks in C#
This file contains hidden or 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
/* | |
`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