I have a simple taken form MS documentation implementation of generic throttle function.
public async Task RunTasks(List<Task> actions, int maxThreads)
{
var queue = new ConcurrentQueue<Task>(actions);
var tasks = new List<Task>();
for (int n = 0; n < maxThreads; n++)
{
tasks.Add(Task.Run(async () =>
{
while (queue.TryDequeue(out Task action))
{
action.Start();
await action;
int i = 9; //this should not be reached.
}
}));
}
await Task.WhenAll(tasks);
}
To test it I have a unit test:
[Fact]
public async Task TaskRunningLogicThrottles1()
{
var tasks = new List<Task>();
const int limit = 2;
for (int i = 0; i < 2000; i++)
{
var task = new Task(async () => {
await Task.Delay(-1);
});
tasks.Add(task);
}
await _logic.RunTasks(tasks, limit);
}
Since there is a Delay(-1) in the tasks this test should never complete. The line "int y = 9;" in the RunTasks function should never be reached. However it does and my whole function fails to do what it is supposed to do - throttle execution. If instead or await Task.Delay() I used synchronous Thread.Sleep ot works as exptected.