I have a console app which uses a class library to execute some long running tasks. The console app is unaware of how many tasks the library executes (some of which run in parallel). I need to be able to report the progress of each task within the console application. The call from my console app looks something like this
public Task StartAsync(CancellationToken cancellationToken) { _myServiceFromLibrary.RunTasks();return Task.CompletedTask;
}
And in my my class library, the implementation is something along the lines of
public void RunTasks()
{
var taskList1 = new List<ITask> { Task1, Task2 }:
var taskList2 = new List<ITask> { Task3, Task4, Task5 }:taskList1.foreach( task => task.Run() ); Parallel.Foreach(taskList2, task => { task.Run() });
}
Now, I want to pass a collection of IProgress<T>
to the RunTasks()
method which I can then iterate over and display the progress individually on the console. These are then passed by RunTasks()
to each task’s Run()
method so the task can report it’s own progress back.
However, to be able to know how many instances I need to pass, I am using a dirty hack where the class library exposes a TaskListCount
which I use to generate those many IProgress<T>
to send to RunTasks()
.
Is there a better way to do this? I am really only after being able to get the progress updates from RunTasks()
somehow, even if it is without using IProgress
.
Any help much appreciated.
#c-sharp #.net #asp.net