如何在繁忙循环期间显示进度?
我有一个循环从外部源读取大量数据。 该过程大约需要 20 秒,我想向用户展示进度。 我不需要任何花哨的进度条,所以我选择在一个标签中绘制我的进度,标签上写着“Step 1/1000”,然后更改为“Step 2/1000”等。
我的代码看起来像这样:
// "count" is the number of steps in the loop,
// I receive it in previous code
String countLabel = "/"+count.ToString();
for (i = 0; i < count; i++)
{
... do analysis ...
labelProgress.Content = "Step "+i.ToString()+countLabel
}
但是,在该分析过程中,屏幕“卡住”并且进度不显示为前进。 我从过去的 C++ 中理解了这种行为,我可能会有一个单独的线程,显示一个进度条,从循环接收通知,或某种形式的重绘/刷新,或强制窗口/应用程序处理其消息队列。
在 C# 中正确的做法是什么? 我不受标签的束缚,所以如果有一个简单的进度条弹出屏幕我可以使用而不是这个标签,它也会很棒......
谢谢
I have a loop that reads plenty of data from an external source. The process takes about 20 seconds, and I want to show the progress to the user. I don't need any fancy progress bars, so I chose to plot my progress in a label that will say "Step 1/1000", then change to "Step 2/1000" etc.
My code looks something like this:
// "count" is the number of steps in the loop,
// I receive it in previous code
String countLabel = "/"+count.ToString();
for (i = 0; i < count; i++)
{
... do analysis ...
labelProgress.Content = "Step "+i.ToString()+countLabel
}
However, during that analysis the screen is "stuck" and the progress does not show as advancing. I understand this behavior from my past in C++, where I would probably have a separate thread showing a progress bar receiving notifications from the loop, or some form of repaint/refresh, or forcing the window/app to process its message queue.
What's the right way to do it in C#? I'm not tied to the label, so if there's a simple progress-bar popup screen I could use instead of this label it would also be great...
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将工作移至 BackgroundWorker 并使用 ReportProgress 方法。
Move the work to a BackgroundWorker and use the ReportProgress method.
UI 不会更新,因为当前线程的优先级高于最终设置标签的 UI 线程;)。 因此,在您的线程完成您的内容之前,它最终会更新您的标签。
对我们来说幸运的是,每个 WPF 控件上都有一个 Dispatcher 属性,可以让您启动具有另一个优先级的新线程。
这会在后台启动一个线程并完成工作! 您还可以尝试其他 DispatcherPriority 选项
PS我还冒昧地添加了一个匿名方法并稍微修复了你的字符串解析..希望你不介意..
The UI is not updated due to the fact that your current thread has a higher priority than your UI thread which will ultimately set the label ;). So until your thread has finished to your stuff it will update your label in the end.
Lucky for us, there is a Dispatcher property on every WPF control that lets you fire up a new thread with another priority..
This fire up a thread in the background and would get the job done! You can also try other DispatcherPriority options
PS I also took the liberty to add an anonymous method and fix your string parsing somewhat.. hope you don't mind..