WPF调度员,后台工作者和很多痛苦 [英] WPF Dispatcher, Background worker and a whole lot of pain

查看:74
本文介绍了WPF调度员,后台工作者和很多痛苦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这可能真的很简单,但是我尝试的一切似乎都碰到了墙.

Ok this may be really simple but everything I try just seems to hit a brick wall.

我有一个具有两个属性的视图模型,这些属性绑定到我的WPF表单:

I have a view model with two properties, which are bound to my WPF form:

 bool IsWorking {get;set;}
 ObservableCollection<OtherViewModel> PendingItems {get;set;}

我有一种方法可以调用,以从Outlook中获取一些新的待处理项目,但是我还要在表单上显示某种进度(旋转进度条),进度条的可见性绑定到了IsWorking属性上. ViewModel,并且网格绑定到PendingItems集合.

I have a method that I call to fetch some new pending items from outlook, however I also what to show some sort of progress on the form(spinning progress bar), the progress bar visibility is bound to the IsWorking property on the ViewModel, and a grid is bound to PendingItems collection.

我希望能够将IsWorking设置为true,以便UI可以显示进度条,在后台运行工作,然后在完成后将IsWorking设置为false,以便进度条消失.

I would like to be able to set the IsWorking to true so the UI can show the progress bar, run the work in the background and then set the IsWorking to false after it's finished so the progress bar goes away.

我创建了一个像这样的backgroudworker:

I created a backgroudworker something like this:

        worker = new BackgroundWorker();
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        worker.RunWorkerAsync();

现在worker_DoWork调用了一种方法,该方法将提取待处理的项目并将其添加到PendingItems集合中,所有操作都在后台运行,UI仍在响应,但是在尝试添加到集合时出现了正常的跨线程错误.我将更改集合的代码包装在调度程序调用中:

Now worker_DoWork calls the method that goes of a fetches the pending items and adds them to PendingItems collection, everything runs in the background the UI is still responsive but I get the normal cross threaded error when trying to add to the collection. I wrapped the code that changes the collection in a dispatcher call:

        // Update to show the status dialog.
        Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Render,
                            new Action(delegate()
                            {
                                this.PendingItems.Add(\\Blah);
                            })
                          );

但是它仍然会引发相同的跨线程错误.

but it still throws the same cross thread error.

我对线程处理不是很好,所以我不知道我可能做错了什么,有人可以帮我吗?

I'm not very good with threading so I have no idea what I might be doing wrong, would someone be able to give me a hand with this?

推荐答案

看看这里,了解有关其他人如何创建线程安全的可观察集合的信息(因此您不必这样做).

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

这篇关于WPF调度员,后台工作者和很多痛苦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆