I'm doing a POC to split a List of strings into batches and process each batch asynchronously.
But when I run the program, it always takes the first set of items (that's 3 as per the batch size). So could anyone please help me how to move to the next set of items.
Take
is an extension method that I have written. And I tried using async/await
pattern for it.
Thanks in advance
public class Program
{
public static async Task Main(string[] args)
{
var obj = new Class1();
List<string> fruits = new()
{
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
};
await Class1.Start(fruits);
Console.ReadLine();
}
}
public class Class1
{
private const int batchSize = 3;
public static async Task Start(List<string> fruits)
{
if (fruits == null)
return;
var e = fruits.GetEnumerator();
while (true)
{
var batch = e.Take(3); // always taking the first 3 items and not moving to the next items of the list
if (batch.Count == 0)
{
break;
}
await StartProcessing(batch);
}
}
public static async Task StartProcessing(List<string> batch)
{
await Parallel.ForEachAsync(batch, async (item, CancellationToken) =>
{
var list = new List<string>();
await Task.Delay(1000);
Console.WriteLine($"Fruit Name: {item}");
list.Add(item);
});
}
}
Extension.cs
public static class Extensions
{
public static List<T> Take<T>(this IEnumerator<T> e, int num)
{
List<T> list = new List<T>(num);
int taken = 0;
while (taken < num && e.MoveNext())
{
list.Add(e.Current);
taken++;
}
return list;
}
}