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

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

问题描述

如何在 C# 中为数据库调用实现进度条和后台工作器?

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;
}

Marquee 样式需要启用 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天全站免登陆