WPF Dispatcher, Background worker and a whole lot of pain WPF Dispatcher, Background worker and a whole lot of pain wpf wpf

WPF Dispatcher, Background worker and a whole lot of pain


have a look here for info on how other people have created thread safe observable collections (so you dont have to).


Since the code to update the collection is being called from a background thread, Dispatcher.CurrentDispatcher is the wrong dispatcher. You need to keep a reference to the UI's dispatcher and use that dispatcher when scheduling the update.


According to http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.currentdispatcherBecause you call Dispatcher.CurrentDispatcher in the new thread (created by worker) it creates new dispatcher object. So you should get dispatcher from the calling thread (ui thread) in some way.Another option is to pass ui dispatcher to worker.RunWorkerAsync(object argument) as argument

worker = new BackgroundWorker();worker.DoWork += new DoWorkEventHandler(worker_DoWork);worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);worker.RunWorkerAsync(Dispatcher.CurrentDispatcher);...private void worker_DoWork(object sender, DoWorkEventArgs e){   Dispatcher dispatcher = e.Argument as Dispatcher; // this is right ui dispatcher   // Update to show the status dialog.   dispatcher.Invoke(DispatcherPriority.Render,                            new Action(delegate()                            {                                this.PendingItems.Add(\\Blah);                            })                          );}