WPF 从 BackgroundWorker 更新进度条的最佳点
我有一项需要很长时间才能执行的任务。为了通知用户进度,我在 DoWork
内更新了一个进度条。
谁能告诉我这是否是更新进度条的最佳方式?我听说有一个 ReportProgress
事件处理程序,但我很困惑,因为我不确定 ReportProgress
的用途。
I have a task that takes a long time to execute. In order to inform the user of the progress, I have a progress bar that I update inside DoWork
.
Can anybody tell me if this is the best way to update the progress bar? I have heard that there is a ReportProgress
event handler but I am confused because I'm unsure of the purpose of ReportProgress
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于后台工作线程在单独的线程中工作,因此如果您尝试访问 UI 对象,就会遇到问题。从 DoWork 处理程序内部调用工作线程的 ReportProgress 方法会引发 ProgressChanged 事件。该事件应在 UI 线程中处理,以便轻松访问控件。
...
Since the Background worker works in a separate thread, you'll run into problems if you try to access UI objects. Calling the ReportProgress method on the worker from inside the DoWork handler raises the ProgressChanged event. That event should be handled in the UI thread so as to easily access the control.
...
ProgressChanged 事件正是您所寻找的。但是,请确保您创建如下所示的BackgroundWorker,以便在调用ReportProgress 时它实际上会引发此事件。
The ProgressChanged event is what you are looking for. However, make sure you create the BackgroundWorker like below so it actually raises this event when ReportProgress is called.
ReportProgress 是您用来更新任务进度的工具,包括 UI 之类的内容 - 在您的例子中是进度条。
您应该查看 MSDN 文档,位于此处。
基本上,您为 ReportProgress 事件创建一个处理程序,然后在 DoWorkEventHandler 中调用 ReportProgress,如下所示:
ReportProgress is what you would use to update the progress of your task, including things like the UI--in your case, a proggress bar.
You should check out the MSDN docs, located here.
basically, you create a handler for the ReportProgress event, then in your DoWorkEventHandler, you call the ReportProgress like so: