Tuesday 23 October 2012

BackgroundWorker Example

In this example, I will use the BackgroundWorker to call several methods (no simultaneously).I will show how to use a Progress Bar control to report the progress of the process, updating the text value in the middle of the control. I also will show how to update the text in a TextBox control, using delegate.



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Threading;
 
 
namespace ExcelFileReader
{
    public partial class Form1 : Form
    {
            private BackgroundWorker bw = new BackgroundWorker();
        delegate void SetTextCallback(string text);
 
 
        public Form1()
        {
            InitializeComponent();
           
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
 
        }
 
        #region Test1
        private void Test1(BackgroundWorker worker, DoWorkEventArgs e)
        {
            SetTextBox1("Stating the process with Test1...");
           
            int LastRow = 100; // This is the reference value for the ProgressBar
            for (int rCnt = 1; rCnt <= LastRow; rCnt++)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Do something here
                   Thread.Sleep(1000); // Replace for your code
                    worker.ReportProgress(((rCnt * 100) / LastRow));
 
                }
            }
            wb.Close();
            worker.ReportProgress(100);
            SetTextBox1("Master File process completed!");
 
        }
        #endregion
 
      private void button1_Click(object sender, EventArgs e)
        {
            if (bw.IsBusy != true)
            {
                    textBox1.Text = "";
                    bw.RunWorkerAsync();
 
                }
            }
           
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            if (bw.WorkerSupportsCancellation == true)
            {
                bw.CancelAsync();
            }
 
        }
 
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
 
            if ((worker.CancellationPending == true))
            {
                e.Cancel = true;
            }
            else
            {
                switch (varstring)
                {
                    case "Test1":
                        Test1(worker, e);
                        break;
                    case "Test2":
                        Test2(worker, e);
                        break;
                    case default:
                        Test3(worker, e);
                        break;
                }
 
            }
        }
 
        private void SetTextBox1(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetTextBox1);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                if (text != "")
                    this.textBox1.Text += text + System.Environment.NewLine;
 
            }
        }
       
 
        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
            this.progressBar1.CreateGraphics().DrawString(e.ProgressPercentage.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(this.progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
        }
 
 
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                this.textBox1.Text = "Canceled!";
            }
 
            else if (!(e.Error == null))
            {
                this.textBox1.Text = ("Error: " + e.Error.Message);
            }
 
            else
            {
                this.textBox1.Text += "Done!";
            }
        }
 
    }
}
 
 
 
In the application, you should add too Button controls (Start and Stop/Cancel), a Progree Bar control, and a TextBox control. We create the BackgroundWorker dinamically in the code, but you can add the BackgroundWorker control.
 
Thanks for reading.