I designed a WPF application based on MVVM pattern and I need to get large amount of data from a webservice, and i do it with a BackgroundWorker inside the ViewModel. To modify the observable collection i have to use a dispatcher and the problem is here, even if i pass by reference UI Dispatcher it dosen’t work, it is like I use the inner dispatcher and my application get freezed until all data are retrived.
I try to get the UI Dispatcher in several ways, Dispatcher.CurrentDispatcher, Application.Dispatcher, App.Current.Dispatcher… doing some researches I read that it should be works, does someone have any suggestions?
Thank you
Marco
Update
Here some code: This is how I pass the Dispatcher to the ModelView
void AppWindow_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = new ModelViewApplication(System.Windows.Threading.Dispatcher.CurrentDispatcher);
}
Then I try to get data in this way
public ModelViewApplication(Dispatcher _dispatcher)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(getData);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completedData);
bw.RunWorkerAsync();
}
public void getData(object sender, DoWorkEventArgs e)
{
_dispatcher.Invoke(DispatcherPriority.Normal,
new Action(
delegate()
{
//Connect to webservice and retrieve data
....
}));
}
It seems like the multithread dosen’t work
Use the
BackgroundWorkerto get your data, then use theRunWorkerCompletedto update theObservableCollection. You shouldn’t need theDispatcherat all