Tuesday, April 6, 2010

How to use a ProgressBar in WPF using the BackgroundWorker class

- Have a xaml file with a progressBar called "progressBar" and a button called "button".  I called my project ProgressBar.  My window is also called ProgressBar instead of Window1.
- The key parts of the file below are:
    1.  create a BackGroundworker object.
    2.  Add the DoWork and RunWorkerCompleted events to the constructor of your function
    3.  Implement the DoWork event of the background worker
    4.  Implement the RunWorkerCompleted event of the background worker
    5.  Call the RunWorkerAsync function of the background worker.  This calls the DoWork function.  When its done the RunWorkercompleted function is called.  You can have DoWork return you something - in my example its a string but it could be any object.
    6.  You set the progressBar.IsIndeterminate to true in the click event and you set it to false in the Runworkercompleted function
  
That's pretty much it. 
=====================================
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Input;

namespace ProgressBar
{
    public partial class ProgressBar : Window
    {
        private BackgroundWorker progressBarWorker;

        public ProgressBar()
        {
            InitializeComponent();

            // Create a Background Worker
            progressBarWorker = new BackgroundWorker();

            // Enable support for cancellation
            progressBarWorker.WorkerSupportsCancellation = true;

            progressBarWorker.DoWork +=
                new DoWorkEventHandler(progressBarWorker_DoWork);
            progressBarWorker.RunWorkerCompleted +=
                new RunWorkerCompletedEventHandler(progressBarWorker_RunWorkerCompleted);
        }

        private void progressBarWorker_RunWorkerCompleted(
            object sender, RunWorkerCompletedEventArgs e)
        {
            this.Cursor = Cursors.Arrow;

            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }

            button.Content = "Start";

            // Reset the ProgressBar's IsInderterminate
            // property to false to stop the progress indicator
            progressBar.IsIndeterminate = false;

          // You can even get a return value from the progressBarWorker using e.result
            string strval = (string)e.Result;
            //do something with strval
            MessageBox.Show(strval);
        }

        private void progressBarWorker_DoWork(
            object sender, DoWorkEventArgs e)
        {
            for (int i = 1; i <= 500; i++)
            {
                if (progressBarWorker.CancellationPending)
                    break;

                Thread.Sleep(50);
            }
            //You can return something from the Worker
            e.Result = "some str";
        }

        private void button_Click(
            object sender, RoutedEventArgs e)
        {
            if (!progressBarWorker.IsBusy)
            {
                this.Cursor = Cursors.Wait;

                // Set the ProgressBar's IsInderterminate
                // property to true to start the progress indicator
                progressBar.IsIndeterminate = true;
                button.Content = "Cancel";

                // Start the Background Worker
                progressBarWorker.RunWorkerAsync();
            }
            else
            {
                progressBarWorker.CancelAsync();
            }
        }

    }
}

No comments: