Wilson
Wilson

Reputation: 8768

Updating Windows Forms GUI while code is running

I've run into some problems while using progress bars in Windows Forms. Say I have an algorithm with ten parts that runs on a button click. After each part, I'd want to update a progress bar on the form to 10% further along. However, when code is running, the Windows Form will not respond or update.

What is the correct do show progress on a form while code is running?

Upvotes: 0

Views: 1879

Answers (2)

SalientBrain
SalientBrain

Reputation: 2551

I suggest use TPL for such operations as more standardized, lightweight, robust and extendable See for ex.: http://blogs.msdn.com/b/pfxteam/archive/2010/10/15/10076552.aspx

Upvotes: 0

Maks Martynov
Maks Martynov

Reputation: 458

You need to use a BackgroundWorker.
A nice example can be found here: http://www.dotnetperls.com/progressbar

using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
    InitializeComponent();
    }

    private void Form1_Load(object sender, System.EventArgs e)
    {
      // Start the BackgroundWorker.
      backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
      for (int i = 1; i <= 100; i++)
      {
        // Wait 100 milliseconds.
        Thread.Sleep(100);
        // Report progress.
        backgroundWorker1.ReportProgress(i);
      }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
      // Change the value of the ProgressBar to the BackgroundWorker progress.
      progressBar1.Value = e.ProgressPercentage;
      // Set the text.
      this.Text = e.ProgressPercentage.ToString();
    }
  }
}

Or you can use something like:

private void StartButtonClick(object sender, EventArgs e)
{
    var t1 = new Thread(() => ProgressBar(value));
    t1.Start();
}

private void ProgressBar(value1)
{
  ProgressBar.BeginInvoke(new MethodInvoker(delegate
  {
      ProgresBar.Value++
  }));
}

Upvotes: 4

Related Questions