0

I writing console application, and it has queue collection, that used as a factory of messages.

Is there some way that collection will raise events when it becames empty.

I just don't want start doing pulling it by myself, checking it from time to time.

I thought using ObservableCollection but I dont see a way to implement raising events when it's becomes empty.

Thanks for help.

Night Walker
  • 20,638
  • 52
  • 151
  • 228
  • Have it in a `while(!string.IsNullorEmpty(message))` loop? (JUST using it as an example -) – TheGeekZn Jul 02 '13 at 12:38
  • @NewAmbition How will checking whether a string is empty or null inform you as to the satus of the collection? – Dave Lawrence Jul 02 '13 at 12:39
  • What is the usage pattern? I suspect you might not want to use events. What will you use the event for? In particular, is there multithreading involved? – Matthew Watson Jul 02 '13 at 12:49

2 Answers2

5

ObservableCollection fires its CollectionChanged event when the contents of the collection change. Just hook that, and in your event handler, check to see if the collection's Count == 0.

Joe White
  • 94,807
  • 60
  • 220
  • 330
0

You could inherit from ObservableCollectionEx and add your own event:

    public class ObservableCollectionEx<T> : ObservableCollection<T>
    {
        public event EventHandler CollectionEmpty;

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (this.Count == 0)
            {
                var eventCopy = this.CollectionEmpty;
                if (eventCopy  != null)
                {
                    eventCopy(this, EventArgs.Empty);
                }
            }

            base.OnCollectionChanged(e);
        }
    }
spender
  • 117,338
  • 33
  • 229
  • 351
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • Your event raising is a potential race condition. Take a read of this: http://broadcast.oreilly.com/2010/09/understanding-c-raising-events.html – spender Jul 02 '13 at 12:43
  • I took the liberty of fixing. – spender Jul 02 '13 at 12:44
  • @spender The famous event race condition ;) There is just *no* answer to this problem. See http://stackoverflow.com/a/786455/870604. And as `ObservableCollection` is not thread safe *per definition*, then there is no point IMO to take care about threading issue. – ken2k Jul 02 '13 at 12:45