I am trying to load some data in a separate thread, then add the loaded data to an ObservableCollection and update the view through ba binding.
First, I was doing the following:
public OverviewViewModel()
{
Thread thread = new Thread(new ThreadStart(delegate
{
TheTVDB theTvdb = new TheTVDB();
foreach (TVSeries tvSeries in theTvdb.SearchSeries("Dexter"))
{
this.Overview.Add(tvSeries);
}
}));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
This gave the following error:
This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.
So I read on this forum that I should use the Dispatcher, so I put this.Overview.Add(tvSeries)
into a call to the Dispatcher.
Dispatcher.CurrentDispatcher.BeginInvoke((Action)delegate
{
this.Overview.Add(tvSeries);
},
DispatcherPriority.Normal);
Now, it doesn't crash anymore but the view is not updated. Nothing happens, the view is just empty. I have tested the functionality by running it on the main thread. Then the view is updated correctly.
Does anyone know why the view is not updated and how I can fix this?
UPDATE
The below approach seems to work and it seems to do everything asynchronously. Can anyone confirm that this is the right approach for doing things asyncronously?
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(delegate
{
TheTVDB theTvdb = new TheTVDB();
foreach (TVSeries tvSeries in theTvdb.SearchSeries("Dexter"))
{
this.Overview.Add(tvSeries);
}
}),
DispatcherPriority.Background);