I am wondering if anyone can help me, I am trying to get my head around how to execute concurrent tasks in batches and apologies if it is a silly question. However, I can only get them to execute all at the same time. I created a class below which is meant to be able to add task(s) to a collection and when the method ExecuteTasks() is called, run the tasks in batches in the order to which they where added in the list. As soon as the tasks are created they start to be executed it seems, is there a way around this.
public class TaskBatches
{
private readonly List<Task> _tasks;
private int _batchSize;
public TaskBatches()
{
_tasks = new List<Task>();
_batchSize = 2;
}
public void Add(Task task)
{
if (task == null)
return;
_tasks.Add(task);
}
public void Add(List<Task> task)
{
if (!task.Any())
return;
_tasks.AddRange(task);
}
public void Add(params List<Task>[] toAdd)
{
if (!toAdd.Any())
return;
foreach (var element in toAdd.SelectMany(items => items))
Add(element);
}
public async Task ExecuteTasks()
{
foreach (var batch in _tasks.Where(x => !x.IsCompleted || !x.IsCanceled).Chunk(_batchSize))
await Task.WhenAll(batch);
_tasks.RemoveAll(x => x.IsCompleted);
}
public void SetBatchSize(int batchSize)
{
_batchSize = batchSize;
}
}