Skip to content

Instantly share code, notes, and snippets.

@mrhammadasif
Last active February 20, 2025 19:56
Show Gist options
  • Save mrhammadasif/9a0fec0376ff0143f15211364aef8886 to your computer and use it in GitHub Desktop.
Save mrhammadasif/9a0fec0376ff0143f15211364aef8886 to your computer and use it in GitHub Desktop.
Process Async Operations in Batches with given Batch Size in C#
public static class BatchOperations
{
public static async Task Process<T>(int batchSize, IReadOnlyList<T> items, Func<IReadOnlyList<T>, Task> processBatch)
{
var processed = 0;
while(processed < items.Count)
{
var batch = items.Skip(processed).Take(batchSize).ToList();
await processBatch(batch);
processed += batchSize;
}
}
}
public class Program {
async public void Main() {
await Process(40, Enumerable.Range(1, 100).ToList(), async batch => {
await Task.Delay(100);
Console.WriteLine($"Processed batch of {batch.Count} items");
});
Console.WriteLine($"Processed 100 items");
}
}
// This will output
// Processed batch of 40 items
// Processed batch of 40 items
// Processed batch of 20 items
// Processed 100 items
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment