在C#中实现进度条的正确方法 [英] The right way to implement a progressbar in C#

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

问题描述

我正在学习Winforms,我为自己设定了一个简单的目标,即制作一个从空到满的进度条.这是我变形的尝试:

I'm learning winforms and I have set myself a simple goal of making a progressbar that goes from empty to full. Here's my misshapen attempt:

public partial class Form1 : Form
{
    static BackgroundWorker bw = new BackgroundWorker();

    public Form1()
    {
        InitializeComponent();
        bw.DoWork += bw_DoWork;
        bw.RunWorkerAsync();
    }

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        for(int i=0; i<100; ++i)
        {
            progressBar1.PerformStep();
            Thread.Sleep(10);
        }
    }
}

我很确定Thread.Sleep()是应该理解的.我在这里如何避免呢?

I'm pretty sure that the Thread.Sleep() is reprehensible. How do I avoid it here?

推荐答案

您已经做得差不多了. BackgroundWorker已经内置了报告进度的机制.

You are already doing it almost right. The BackgroundWorker has a built in mechanism for reporting progress already.

public Form1()
{
    bw1.WorkerReportsProgress = true;
    bw1.ProgressChanged += bw1_ProgressChanged;
    bw1.DoWork += bw1_DoWork;

    bw1.RunWorkerAsync();
}

private void bw1_DoWork(object sender, DoWorkEventArgs e)
{
    var worker = sender as BackgroundWorker;

    while (workNotDone)
    {
        //Do whatever work
        worker.ReportProgress(CalculateProgressDonePercentage());
    }
}

private void bw1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    //This is called on GUI/main thread, so you can access the controls properly
    progressBar.Value = e.ProgressPercentage;
}

当然,除非您只是尝试为进度条设置动画而不实际报告任何进度,在这种情况下,您可能应该只使用Marquee类型,该类型将自动滚动进度条而不执行任何操作.或仅将背景线程与Thread.Sleep()一起使用.

Unless of course you're just trying to animate a progress bar without actually reporting any progress, in which case you should probably just use the Marquee type that will automatically scroll a progressbar without doing anything. Or just use a background thread with Thread.Sleep().

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

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