TriggeredQueue

I'm working on a Xamarin iOS/Android mobile project in which the core view of the app displays some images and data from some web calls. The app designer didn't like the way that images loaded AFTER they scrolled onto the screen (think Facebook). So, I had to come up with a way to load the images in the background so that they were immediately available as each view scrolled onto the screen.

This seemed like a good job for the .NET Queue<T> class. However, that class contains no way to get notifications when items are enqueued and dequeued from the collection. So, I put together a TriggeredQueue<T> class to help me out with this.

It contains four events:

  • WillEnqueue
  • WillDequeue
  • DidEnqueue
  • DidDequeue

You use it like this:

YourQueue.DidEnqueue += (sender, e) => { 
    /* kick off some process */
};

or this:

YourQueue.DidEnqueue += (sender, e) => { 
    DoSomething(e.EnqueuedItem);
    DoSomethingElse(e.PreviousHeadOfQueue);
};

You can keep the queue perpetually full by:

  1. setting up a queueSize variable some place near where you're using the TriggeredQueue<T>
  2. hook into the DidDequeue method as demonstrated above and check if YourQueue.Count < queueSize
  3. if it's true, then kick off some process to get your data, then feed each resulting item into YourQueue with the Enqueue() method
  4. when you want to get an item from YourQueue, call the Dequeue() method, which will kick off the DidDequeue event you hooked into

Cool! A queue that perpetually keeps itself filled!

comments powered by Disqus