Question

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

Was it helpful?

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.

OTHER TIPS

You can implement the event:

public class YourClassName
{
    private List<Type> m_InnerList = new List<Type>();

    public event EventHandler OnBatch;

    public void Add(Type object)
    {
        m_InnerList.Add(object);
        if ((m_InnerList.Count % YourCountHere == 0) && OnBatch != null)
           OnBatch(this, new EventArgs());

    }

}

You will have to change the name, choose your type (or make the class generic too), implement more logic (like accessing your items) - and you can change it to get the batch amount in the constructor

you can derive from List instead

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top