如何实现在C#中的进度条? [英] How do I implement a progress bar in C#?

查看:258
本文介绍了如何实现在C#中的进度条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在C#中实现一个进度条和BackgroundWorker的数据库调用?

How do I implement a progress bar and backgroundworker for database calls in C#?

我有一个处理大量数据的一些方法。他们是相对长期运行的操作,所以我想实现一个进度条,让用户知道什么是实际发生的事情。

I do have some methods that deal with large amounts of data. They are relatively long running operations, so I want to implement a progress bar to let the user know that something is actually happening.

我想用进度栏或状态带标签的,但因为有一个单一的UI线程,其中数据库,交易方法的执行线程,UI控件不更新,使进度栏或状态带标签是没有用的给我。

I thought of using progress bar or status strip label, but since there is a single UI thread, the thread where the database-dealing methods are executed, UI controls are not updated, making the progress bar or status strip label are useless to me.

我已经看到了一些例子,但他们处理的for循环,例如:

I've already seen some examples, but they deal with for-loops, ex:

for(int i = 0; i < count; i++)
{ 
    System.Threading.Thread.Sleep(70);
    // ... do analysis ...
    bgWorker.ReportProgress((100 * i) / count);
}

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

我在寻找更好的例子。

I'm looking for better examples.

推荐答案

有些人可能不喜欢它,但是这是我做的:

Some people may not like it, but this is what I do:

private void StartBackgroundWork() {
    if (Application.RenderWithVisualStyles)
        progressBar.Style = ProgressBarStyle.Marquee;
    else {
        progressBar.Style = ProgressBarStyle.Continuous;
        progressBar.Maximum = 100;
        progressBar.Value = 0;
        timer.Enabled = true;
    }
    backgroundWorker.RunWorkerAsync();
}

private void timer_Tick(object sender, EventArgs e) {
    if (progressBar.Value < progressBar.Maximum)
        progressBar.Increment(5);
    else
        progressBar.Value = progressBar.Minimum;
}

选取框风格需要VISUALSTYLES被启用,但是它连续滚动自身无需进行更新。我利用它来进行数据库操作不报告进度。

The Marquee style requires VisualStyles to be enabled, but it continuously scrolls on its own without needing to be updated. I use that for database operations that don't report their progress.

这篇关于如何实现在C#中的进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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