Tuesday, March 1, 2011

ObservableQueue?

Has anyone written a version of .Net's generic Queue that implements INotifyCollectionChanged, or is there one hidden deep in the .Net framework somewhere already?

From stackoverflow
  • A quick search didn't show any results. But the interface is simple and it would be almost trivial to extend the Queue class and add support for the interface. Just override all methods thusly:

    // this isn't the best code ever; refactor as desired
    protected void OnCollectionChanged( NotifyCollectionChangedEventArgs ccea){
      var temp = CollectionChanged;
      if(temp != null) temp(this, ccea);  
    }
    
    // and later in the class
    
    public override SomeMethodThatAltersTheQueue(object something){
      // record state of collection prior to change
      base.SomeMethodThatAltersTheQueue(something)
      // create NotifyCollectionChangedEventArgs with prior state and new state
      OnCollectionChanged(ccea);
    }
    
    C. Lawrence Wenham : Unfortunately, the .Net generic Queue class does not allow Enqueue() or Dequeue() to be overridden in a descendant class.
    C. Lawrence Wenham : I ended up making an ObservableQueue class that uses method hiding to override Enqueue() and Dequeue(). As long as the code enqueueing or dequeueing does it on the Queue As ObservableQueue, and not just polymorphicly as a regular Queue, the events will fire.
    Will : A better one might be not to override but to create a new queue (no IQueue interface! weird!) that takes a Queue in a constructor and just pass method calls to the internal collection
  • This is the best generic queue lib around

    http://www.itu.dk/research/c5/

    It implements a FIFO Queue but doesnt have the interface you require... but suppose you could extened

  • There is the ObservableCollection. But you have probably already found that.

  • I used the same approach as Chris Wenham. Under load, performance suffers because new NotifyCollectionChangedEventArgs need to be allocated for each Enqueue/Dequeue.

    Regardless, in the Enqueue, send args with NotifyCollectionChangedAction.Add, the item added, and Count-1 as the index. In the Dequeue, send args with NotifyCollectionChangedAction.Remove, the item removed, and index 0.

0 comments:

Post a Comment