Forum Xamarin.Forms


The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Binding to list causing race conditions

larsvlarsv Member ✭✭
edited August 2020 in Xamarin.Forms

I have an ICollectionChanged list bound to a ListView.
This list changes based on external factors, and the Listview responds to changes by refreshing its content.

However, from time to time I get an exception where the Listview apparently is enumerating the content of the list, while the list content is changing, for example when the list is cleared while the ListView is enumerating the list.

What is a good pattern for eliminating this race condition?

One approach is to not update the list, but rather replace the binding with a new copy of the list when content changes. That is however not ideal, as the ListView listens to CollectionChanged events such as Add and Remove and handles those events in an elegant way. Replacing the binding at any change will cause the entire ListView to be refreshed for any collection change.

Another approach would be to somehow gate CollectionChanged notifications to let the ListView complete its enumeration before getting the next update event. Not sure how to do that though.

Yet another possible approach is to introduce a delay between CollectionChanged notifications, to let the ListView catch up. I think I like that approach.


  • JohnHardmanJohnHardman GBUniversity admin


    Are you raising the CollectionChanged events from a worker thread instead of the UI thread?

  • larsvlarsv Member ✭✭

    @JohnHardman said:

    Are you raising the CollectionChanged events from a worker thread instead of the UI thread?

    No, CollectionChanged events are always on the UI thread. I think I get Exceptions from the ListView otherwise.

  • larsvlarsv Member ✭✭
    edited August 2020

    I have created a workaround:

    The event that causes the list to update is filtered/delayed so that updates happen at least 1000 ms apart. In my use case that's fully acceptable. This seems to avoid the race condition completely, at least on the platform I tested. Perhaps the delay needs to be tweaked for different scenarios/platforms.

Sign In or Register to comment.