WPF Dispatcher, Background worker and a whole lot of pain

ぃ、小莉子 提交于 2019-12-03 15:58:36

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.currentdispatcher Because 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);
                            })
                          );

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!