The Task.WaitAny
is not working as expected. I have a very simple application as below:
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
List<Task> _TaskList = new List<Task>();
int iTaskIndex;
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("--------------------------------");
if (_TaskList.Count >= 3)
{
iTaskIndex = Task.WaitAny(_TaskList.ToArray(), stoppingToken);
// Not working as expected,
// expecting this will result index of task which has completed
_logger.LogInformation("iTaskIndex - {0}", iTaskIndex);
if (iTaskIndex >= 0)
{
_TaskList.RemoveAt(iTaskIndex);
}
}
_TaskList.Add(Task.Factory.StartNew(() => TimeConsumingTask()));
await Task.Delay(1000, stoppingToken);
}
}
private async void TimeConsumingTask()
{
_logger.LogInformation("TimeConsumingTask started {task} running at: {time}",
Task.CurrentId, DateTimeOffset.Now);
await Task.Delay(1000 * 60);
_logger.LogInformation("TimeConsumingTask completed {task} running at: {time}",
Task.CurrentId, DateTimeOffset.Now);
}
}
At any given moment I should not have more than 3 tasks running simultaneously. I am deriving the index of completed task as:
iTaskIndex = Task.WaitAny(_TaskList.ToArray(), stoppingToken);
I am expecting that it will return index of completed task only. But I am getting index 0 everytime. The Task.WaitAny
method describes:
Waits for any of the provided System.Threading.Tasks.Task objects to complete execution unless the wait is cancelled.
Am I missing something, or my understanding is not correct?