Search code examples
c#.netcallbackicollectionbatching

How to create Callback Event on ICollection in C# - for batching


Is there a way to create a callback function that fires when a list object (any Class implementing the ICollection interface of C#.NET) reaches a certain capacity (number of items in the list)?

I would like an event to fire when my list object has 5 elements for example.

To place you in context, I am doing that to batch data processing since I am running a service that utilizes HTTP over the network and batching is necessary for the performance of my application.

a simple implementation is batching in memory (in a list) and fire when it reaches some capacity and then send over the network or if there are other tools I would appreciate any pointers to them.

Thanks


Solution

  • There's no way to add the event to every ICollection class that already exists, but you could use either ObservableCollection or BindingList as alternatives. Both of those will raise an event when the list changes so you could just check the item count in the changed event. Alternatively, you could create your own class that implements ICollection simply wrapping the methods of an internal List object and add special code to the Add method to check the count.