Last active
February 20, 2025 19:56
-
-
Save mrhammadasif/9a0fec0376ff0143f15211364aef8886 to your computer and use it in GitHub Desktop.
Process Async Operations in Batches with given Batch Size in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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