0

I have a ObservableCollection bound to a DataGrid. I would like to update the collection inside another class that runs a async function. Currently when I try to add it normally I get the error : This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread. Reading other questions many suggest using BindingOperations.EnableCollectionSynchronization but I have no idea how to implement it and I can't find any examples that run it from another class. Is this this the right way to update the collection, as they would be updated very frequently, or is there some better way?

As for the code, Main class:

public DataStore dataStore = new DataStore();
public MainWindow() {

 InitializeComponent();
 requestView.ItemsSource = dataStore.requestData;
 responseView.ItemsSource = dataStore.responseData;

 DataRetriver drt = new DataRetriver(dataStore);
}

And the class that retrives data:

public class DataRetriver 
{
 DataStore localStore;
 public BidAskDataRetriver(DataStore ds) 
 {
  this.localStore = ds;
  runA();
 }

 public void runA() 
 {
  //Build listener
  listener.Bind("data", (dynamic data) => {
   //data = json
   parseData(data);
  });
 }

 parseData(dynamic data) 
 {
  //parse data and make a list with items for collection
  foreach(myClass item in items)
   localStore.requestData.Add(item);
 }
}
Hauba
  • 75
  • 3
  • 8
  • Show minimal relevant code. – Hamlet Hakobyan Jul 31 '16 at 21:11
  • @HamletHakobyan I added some code, hope its relevant enough. – Hauba Jul 31 '16 at 22:26
  • Possible duplicate of [Why isn't it possible to update an ObservableCollection from a different thread?](http://stackoverflow.com/questions/2980642/why-isnt-it-possible-to-update-an-observablecollection-from-a-different-thread) – AnjumSKhan Aug 01 '16 at 05:59
  • duplicate of http://stackoverflow.com/questions/2980642/why-isnt-it-possible-to-update-an-observablecollection-from-a-different-thread?rq=1 – AnjumSKhan Aug 01 '16 at 05:59

1 Answers1

0

You can use Dispatcher to do this. And to use dispatcher you have to keep a Dispatcher instance. For example you can send UI dispatcher via you class constructor like this and store it in "dispatcher":

DataRetriver drt = new DataRetriver(dataStore, requestView.Dispatcher);

Then the following code will do the job but know this, Dispatcher tasks run on UI thread therefore the more operations you send to Dispatcher the less background process you do the doing things in different threads is less useful. So you might consider creating your list in another object in background and set it to the original object in one step (not in a loop).

 parseData(dynamic data) 
 {
   //parse data and make a list with items for collection
   foreach(myClass item in items)
   {
      dispatcher.Invoke(()=>{
         localStore.requestData.Add(item);
      });
   }
 }
Emad
  • 3,809
  • 3
  • 32
  • 44