我怎么忙循环中显示进度? [英] How do I display progress during a busy loop?

查看:139
本文介绍了我怎么忙循环中显示进度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#和WPF,很新的两种工作。

I'm working in C# and WPF, very new to both.

我有一个循环,从外部源读取大量数据。这个过程大约需要20秒,我想表明的进展给用户。我不需要任何花哨的进度条,所以我选择在绘制一个标签,会说步骤1/1000我的进步,然后更改为步2/1000等。

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.

我的code看起来是这样的:

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
}

不过,分析过程中屏幕显示为卡住,进度不显示,作为推进。据我所知,从我在C ++中,过去的这种行为,我想可能有一个单独的线程显示进度条从环路接收通知,或某种形式重绘/刷新的,或者强迫窗口/应用程序来处理它的消息队列。

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.

什么是做在C#中的正确方法?我不依赖于标签,所以如果有一个简单的进度条弹出屏幕,我可以代替使用这个标签也将是巨大的......

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...

感谢

推荐答案

移动工作提高到一个的 BackgroundWorker的并使用 ReportProgress 方法。

Move the work to a BackgroundWorker and use the ReportProgress method.

for (i = 0; i < count; i++)
{
    ... do analysis ...
    worker.ReportProgress((100 * i) / count);
}

private void MyWorker_ProgressChanged(object sender,
    ProgressChangedEventArgs e)
{
    taskProgressBar.Value = Math.Min(e.ProgressPercentage, 100);
}

这篇关于我怎么忙循环中显示进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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