I am adding Background Tasks to a Blocking Collection (added in the Background).
I am waiting with Task.WhenAll on a Enumerable returned by GetConsumingEnumerable.
My question is: Is the overload of Task.WhenAll which receives an IEnumerable "prepared" to potentially receive an endless amount of tasks?
I am simply not sure if i can do it this way or if it was meant to be used this way?
private async Task RunAsync(TimeSpan delay, CancellationToken cancellationToken)
{
using (BlockingCollection<Task> jobcollection = new BlockingCollection<Task>())
{
Task addingTask = Task.Run(async () =>
{
while (true)
{
DateTime utcNow = DateTime.UtcNow;
var jobs = Repository.GetAllJobs();
foreach (var job in GetRootJobsDue(jobs, utcNow))
{
jobcollection.Add(Task.Run(() => RunJob(job, jobs, cancellationToken, utcNow), cancellationToken), cancellationToken);
}
await Task.Delay(delay, cancellationToken);
}
}, cancellationToken);
await Task.WhenAll(jobcollection.GetConsumingEnumerable(cancellationToken));
}
}
Parallel.Foreach(Repository.GetAllJobs,....)
would be a simpler solution. – BlancheTask.WhenAll
will block the calling thread tillGetConsumingEnumerable
finishes – CreelWhenAll
doesn't yield control until it has been able to enumerate all of the items in the sequence it's given. – BlattWhenAll
at all, just wait on that cancellation token. – Blatt