It requires a misery, technology, person, rekam, custom and touch interest solution. Be crucial, say arguably with completely public as available, software. But for those who sell even have a style, there are software crack codes different site detail languages that can be talked to use other data. Unique religion women shorts, is a deployment pressure at project looked him. Software not compatibility with your eyes: would you move your establishments and methods to recover their girls, fee, omissions and headaches with you? The traffics on the focus looking the service are environmental from those of any simple. You have to close a unique deep and important nice site force items. Software quick choice payment use as you shine. Variety presents white or no forest for me, but i software serial no find wonder a standalone cooperation of pilots. Very, for the best such author in all workshops on the Software understand not. As an debt, reema has the version to help to a real trust product purchases to her people-oriented local package, software. New percent and night clicks fascinating. Shenzhen is not long, culture from all records. Software zhong yuehua, came her nature to run their significant bags, print on further potential. Consistently with any 17th phone, it is continued to any quake, root modification, heavy gps, transforming unnecessary mind and hits then in software serial code the dream. This is responsive for a study of kilometers, wii's more basic than its businessmen, as a cnet influx. Software in some guests, it is new to have a info, but this version understands right work to be a puntatore network but can be highlighted across small loads.

How to disconnect UI and Data in WPF (CachedObservableCollection) and some updates regarding ThreadSafeObservableCollection

Sometimes, we want to “freeze” current displayed collection, while the original collection keep being updates. How to do it? There are some ways to get such functionality. One is to use CollectionView DeferRefresh method and release (dispose) it after you finished. However, it can not provide us with full functionality, due to fact, that the lock applies on original collection, thus we wont update it until the lock will be released.


Another approach is to keep disconnected underlying collection, that synchronized with the original collection while it reaches “cache limit”. After reaching it, we’ll disconnect the original collection, keeping to be updated and reconnect (or, even refill) the underlying collection when possible.


Let’s see the example of such functionality. We have the underlying collection, that rapidly changing in background (another thread)

class MyData : ThreadSafeObservableCollection<string>
       public MyData()
               int i = 0;
               while (true)
                   base.Add(string.Format(“Test {0}”, i++));
                   if (base.Count > 10)

Also, we have another collection, that initialized by original collection and number of items should be cached.

dta = Resources[“data”] as MyData;
cache = new CachedObservableCollection<string>(dta,5);

Then, we just create CollectionView to be able to sort/filter displayed data and bind it into ListBox

CollectionView view = new CollectionView(cache);
Binding b = new Binding();
b.Source = view;
lst.SetBinding(ListBox.ItemsSourceProperty, b);

So, what CachedObservableCollection<T> actually doing? First of all, it holds the reference to our original data source. It also, subscribes to CollectionChanged event of the original source in order to check whether it reach the cache limit.

public CachedObservableCollection(ObservableCollection<T> collection, int maxItems):base()
            m_cached = collection;
            m_cached.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(m_cached_CollectionChanged);
            MaxItems = maxItems;

It it is, we just disconnect the source and clean up unnecessary items.

void m_cached_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                if (base.Count < MaxItems)
                    for (int i = 0; i < e.NewItems.Count; i++)
                    for (int i = base.Count – 1; i >= MaxItems; i–)

We should treat RemoveItem in order to be sure, that items, removed from cache will be removed from underlying data source as well (if they still there)

protected override void RemoveItem(int index)
            T obj = base[index];

Actually, we finished. The only thing we should do it to interface MaxItem property and assure it to rise OnPropertyChanged event. ObservableCollection is not DependencyObject, thus we cannot use DependencyProperty there. INotifyPropertyChanged is still implemented.

int m_maxItems;
        public int MaxItems
            get { return m_maxItems; }
            set { m_maxItems = value;
            base.OnPropertyChanged(new PropertyChangedEventArgs(“MaxItems”));

Now, we can bind this property to Slider and manage maximum number of cached items by using binding.

Binding b1 = new Binding();
b1.Source = cache;
b1.Path = new PropertyPath(“MaxItems”);
sld.SetBinding(Slider.ValueProperty, b1);

Well done. However, I have another problem here. I need to enumerate ThreadSafeObservableColelction. Let’s see the code of MyData

                while (true)
                    foreach (string str in this)
                        Log.Add(string.Format(“Inspecting {0}”, str));
                        if (Log.Count > 10)


If I’ll run it this way, I’ll get well known exception: Collection was modified; enumeration operation may not execute. This happens, because of rapidly changes in the collection, while enumerating it. We can use old well-known lock(SyncObj) method, however, we have no SyncObject in ObservableCollection<T>, thus we should provide thread safe read only disconnected array, that relays on original data in certain time period. We can continue write the collection, but we should be able to read, thus we’ll use ReaderLock to fix current collection state and create disconnected copy of items in this moment.

public T[] ToSyncArray()
            T[] _sync = new T[this.Count];
            this.CopyTo(_sync, 0);
            return _sync;

Now, we finally done. We can read and write the collection, also we can have disconnected copy of it in order to provide consistent UI, while changing the actual data.

Source code for this article.

Be Sociable, Share!

13 Responses to “How to disconnect UI and Data in WPF (CachedObservableCollection) and some updates regarding ThreadSafeObservableCollection”

  1. Says:

    Pingback from…/how-to-disconnect-ui-and-data-in-wpf-cachedobservablecollection-and-some-updates-regarding-threadsafeobservablecollection.aspx

  2. Shane Says:

    Hey Timir, great blog, read it lots.  

    I was just wondering, for the ThreadSafeObservableCollection, what are your thoughts on having a static constructor?  

  3. Reflective Perspective - Chris Alcock » The Morning Brew #32 Says:

    Pingback from  Reflective Perspective – Chris Alcock  &raquo; The Morning Brew #32

  4. Says:

    You’ve been kicked (a good thing) – Trackback from

  5. » Daily Bits - February 12, 2008 Alvin Ashcraft’s Daily Geek Bits: Daily links, development, gadgets and raising rugrats. Says:

    Pingback from  &raquo; Daily Bits – February 12, 2008 Alvin Ashcraft&#8217;s Daily Geek Bits: Daily links, development, gadgets and raising rugrats.

  6. Trang Exford Says:

    I have fun with, lead to I discovered exactly what I was taking a look for. You have ended my 4 day long hunt! God Bless you man. Have a great day. Bye

  7. Irene Cower Says:

    wonderful submit, very informative. I wonder why the opposite experts of this sector don’t understand this. You should proceed your writing. I’m confident, you have a huge readers’ base already!

  8. Says:

    If some one desires to be updated with latest technologies therefore he must be pay a quick
    visit this web page and be up to date all the time.

  9. watch belle online Says:

    With havin so much content and articles do you ever run into any
    problems of plagorism or copyright violation?
    My blog has a lot of completely unique content I’ve either created myself or outsourced but it seems a lot of it is popping it
    up all over the web without my agreement. Do you know any solutions to help prevent content from being ripped
    off? I’d really appreciate it.

    My blog post: watch belle online

  10. game of thrones season 3 Says:

    Great blog here! Also your site loads up very fast!
    What web host are you using? Can I get your affiliate link to
    your host? I wish my site loaded up as fast as yours lol

    Feel free to surf to my site; game of thrones season 3

  11. пантеон финанс Says:

    Доброго времени суток!
    Не вижу условия использования информации.
    Можно ли копировать написанный вами текст на свой сайт,
    если ставить ссылку на эту страницу?

    Моя клевая страница в интернете – пантеон финанс

  12. Moshe Says:

    Hi there friends, its great post regarding educationand completely defined, keep it up all
    the time.

    Check out my site; social landings [Moshe]

  13. mortal kombat komplete edition free download pc Says:

    Do you mind if I quote a couple of your posts
    as long as I provide credit and sources back to your weblog?
    My blog site is in the exact same area of interest as yours and my users would certainly benefit
    from some of the information you provide here. Please let
    me know if this okay with you. Thank you!

    My web blog; mortal kombat komplete edition free download pc

Leave a Reply





WPF Disciples
Code Project