In my program I'm starting parallel tasks one by one (http requests), doing it far ahead of any actual results those tasks can return.
It looks like
while (continueTaskSwarming == true)
{
Task.Run(() => Task());
}
Of course that way I have way more tasks scheduled than can be processed, so when I cancel them through cancellation token, it takes a lot of time to just cancel them all - they are scheduled after all, so they must actually run before they can be cancelled.
How can I organize task creation so that there always be only limited bunch of tasks ready to run, with new tasks scheduled only when there is some "place" for them? I mean, some "straight" way, something like
while (continueTaskSwarming == true)
{
PauseUntilScheduledTaskCountIsLowerThan(100);
Task.Run(() => Task());
}
Is that possible?
EDIT:
The obvious way, I think, is to put all tasks created into some list, removing them on completion and checking count of active/scheduled tasks. But I don't know (and don't know keywords to google it) if I can "remove" task from itself, or from ContinueWith() method. Anyone knows?