Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The right way to implement a progressbar in C#

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

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

like image 446
Hui Avatar asked Dec 22 '22 13:12

Hui


1 Answers

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

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

like image 188
SirViver Avatar answered Jan 06 '23 09:01

SirViver