0

I have a question concerning the comparison of ObservableCollections. Basically, in my scenario I have a business logic method that gets a set of items from database for current user in form of ObservableCollection. Periodically, a BackgroundWorker should get user items from DB using aforementioned method, compare them for changes and if any are detected it should trigger an update on UI. The problem is, even if no changes were done to data in DB, the ObservableCollections are always different.

Method used in BackgroundWorker:

private void UpdateItemList(object sender, DoWorkEventArgs e)
{
    const int updateInterval = 30000;

    while (isItemWorkerRunning)
    {
        Thread.Sleep(updateInterval);
        Application.Current.Dispatcher.Invoke(() => ForceUpdateItemList());
    }
}

private void ForceUpdateItemList()
{
    var userItems = GetItems(userId);

    if (lastUserItems!=userItems)
    {
        //force update
        lastUserItems = userItems;
        //update UI
    }
}

What am I doing wrong?

Konrad
  • 1,014
  • 1
  • 13
  • 24

1 Answers1

1

I assume the GetItems(userId) method is returning a new Observable collection and since it is a reference type they will not be equal. The new userItems object is different to the lastUserItems object so the equality fails.

In your case, it would be best to compare the data in lastUserItems to the data in userItems to check for changes.

You may want to look at this question (Check if two collections are equal) since its quite similar

Community
  • 1
  • 1
momar
  • 364
  • 1
  • 3