Is there a .NET queue class that allows you to delete multiple items at once?

I believe that a fairly common scenario is to have a queue of elements that need to be processed N at a time.

For example, if we have 23 items and need to process 10 at a time, this would be like this:

 Process batch of 10 Process batch of 10 Process batch of 3 

I can solve this problem in various ways. My question is: does the .NET framework support any class specifically designed to solve this scenario? The Queue class would be perfect, but it does not allow multiple elements to be challenged at once.

+5
source share
2 answers

You can create an extension method on Queue<T> :

 public static class QueueExtensions { public static IEnumerable<T> DequeueChunk<T>(this Queue<T> queue, int chunkSize) { for (int i = 0; i < chunkSize && queue.Count > 0; i++) { yield return queue.Dequeue(); } } } 

Using:

 var q = new Queue<char>(); q.DequeueChunk(10) // first 10 items q.DequeueChunk(10) // next 10 items 

Example: https://dotnetfiddle.net/OTcIZX

+10
source

The TPL data flow library offers a BatchBlock <T> that groups the input message sequence into chunks of the required size.

  var bb = new BatchBlock<int>(10); var ab = new ActionBlock<int[]>((Action<int[]>)chunk=>HandleChunk(chunk)); bb.LinkTo(ab, new DataflowLinkOptions(){PropogateCompletion = true}); for(int i = 0; i < 23; ++i) { bb.Post(i); } bb.Complete(); ab.Completion.Wait(); 
+1
source

Source: https://habr.com/ru/post/1235314/


All Articles