Search code examples
c#.netwinformsprogress-bar

How do I implement a progress bar in 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.

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.

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.


Solution

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

    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.