If you do not need strict FIFO, I think you should use BlockingCollection .
It is thread safe and the implementation will look something like this:
var collection = new BlockingCollection<Data>(); var sqlinserter = Task.Factory.StartNew(UpdateSql()); while (true) { Data statistics = FetchStatistics(); if (statistics == null) break; collection.Add(statistics); } collection.CompleteAdding(); sqlinserter.Wait();
Edit Saw that you want to insert a certain number of elements in each batch
void UpdateSql() { var batch = new List<Data>(); foreach (var item in collection.GetConsumingEnumerable()) { batch.Add(item); if (batch.Count > SomeBatchSize) { InsertIntoSql(batch); batch.Clear(); } } if (batch.Count > 0) InsertIntoSql(batch);
source share