MGZ NetArt

Software Development and Support

Home
Design Patterns
C# Tips
AsyncCallback
Asynchronous Form.ShowDia
BackgroundWorker
Connection String
CopyTo() vs Clone()
Convert Color To String
Dispose vs Finalize
Debug mode
Delete Duplicate in SQL
Drag&Drop for TreeView
Edit Full Path Property
Hiding And Overriding
Polimorphism
How to use Resources
Run Time DLL
Simple Threading
Singleton Connection
Save Win Form as JPG File
Save Object in Registry
Soap Serialization
Sort and CompareTo
Working With List<>
Examples & Videos
MRDS Examples
Resume
Contact Us
BackgroundWorker
This is example how to use BackgroundWorker control to implement multithreading.
Application simulates a Car Race. Each of the cars are represented by child frmCar  forms of the main CarRace form.
For some additional information I would recommend this page from Microsoft


 

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;

 

namespace Multithreading

{

    public  class CarRace : Form

    {

        private int childFormNumber = 0;

 

        public int whofinished = 0;

        public CarRace()

        {

            InitializeComponent();

        }

 

        private void AddNewCar(object sender, EventArgs e)

        {

            frmCar f = new frmCar();

            f.MdiParent = this;

            f.Text += " " + this.MdiChildren.Length.ToString();

 

            f.Show();

        }

 

        private void StartRace(object sender, EventArgs e)

        {

            whofinished = 0;

            foreach (frmCar f in this.MdiChildren)

            {

                f.StartRacing();

            }

        }

 

 

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)

        {

            this.Close();

        }

 

        //designer

        /// <summary>

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.IContainer components = null;

 

        /// <summary>

        /// Clean up any resources being used.

        /// </summary>

        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

        protected override void Dispose(bool disposing)

        {

            if (disposing && (components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }

 

        #region Windows Form Designer generated code

 

        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

            this.components = new System.ComponentModel.Container();

            this.menuStrip = new System.Windows.Forms.MenuStrip();

            this.operationsMenu = new System.Windows.Forms.ToolStripMenuItem();

            this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();

            this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();

            this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();

            this.menuStrip.SuspendLayout();

            this.SuspendLayout();

            //

            // menuStrip

            //

            this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {

            this.operationsMenu});

            this.menuStrip.Location = new System.Drawing.Point(0, 0);

            this.menuStrip.Name = "menuStrip";

            this.menuStrip.Size = new System.Drawing.Size(632, 24);

            this.menuStrip.TabIndex = 0;

            this.menuStrip.Text = "MenuStrip";

            //

            // operationsMenu

            //

            this.operationsMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {

            this.newToolStripMenuItem,

            this.openToolStripMenuItem,

            this.exitToolStripMenuItem});

            this.operationsMenu.ImageTransparentColor = System.Drawing.SystemColors.ActiveBorder;

            this.operationsMenu.Name = "operationsMenu";

            this.operationsMenu.Size = new System.Drawing.Size(77, 20);

            this.operationsMenu.Text = "&Operations";

            //

            // newToolStripMenuItem

            //

            this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;

            this.newToolStripMenuItem.Name = "newToolStripMenuItem";

            this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));

            this.newToolStripMenuItem.Size = new System.Drawing.Size(169, 22);

            this.newToolStripMenuItem.Text = "&New Car";

            this.newToolStripMenuItem.Click += new System.EventHandler(this.AddNewCar);

            //

            // openToolStripMenuItem

            //

            this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;

            this.openToolStripMenuItem.Name = "openToolStripMenuItem";

            this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));

            this.openToolStripMenuItem.Size = new System.Drawing.Size(169, 22);

            this.openToolStripMenuItem.Text = "&Start Race";

            this.openToolStripMenuItem.Click += new System.EventHandler(this.StartRace);

            //

            // exitToolStripMenuItem

            //

            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";

            this.exitToolStripMenuItem.Size = new System.Drawing.Size(169, 22);

            this.exitToolStripMenuItem.Text = "E&xit";

            this.exitToolStripMenuItem.Click += new System.EventHandler(this.ExitToolsStripMenuItem_Click);

            //

            // CarRace

            //

            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

            this.ClientSize = new System.Drawing.Size(632, 453);

            this.Controls.Add(this.menuStrip);

            this.IsMdiContainer = true;

            this.MainMenuStrip = this.menuStrip;

            this.Name = "CarRace";

            this.Text = "CarRace";

            this.menuStrip.ResumeLayout(false);

            this.menuStrip.PerformLayout();

            this.ResumeLayout(false);

            this.PerformLayout();

 

        }

        #endregion

 

 

        private System.Windows.Forms.MenuStrip menuStrip;

        private System.Windows.Forms.ToolStripMenuItem operationsMenu;

        private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;

        private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;

        private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;

 

 

    }

}

 

 

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;

 

namespace Multithreading

{

    public class frmCar : Form

    {

 

        delegate int AddValueCallBack(int value);

        delegate int GetSpeedCallBack();

        delegate void StartCallBack();

        private void btnStart_Click(object sender, EventArgs e)

        {

            StartRacing();

        }

 

        public void StartRacing()

        {

            if (!backgroundWorker1.IsBusy)

            {

                lblStatus.Text = "I am running";

                backgroundWorker1.RunWorkerAsync(2000);

 

            }

        }

 

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

        {

            // Do not access the form's BackgroundWorker reference directly.

            // Instead, use the reference provided by the sender parameter.

            BackgroundWorker bw = sender as BackgroundWorker;

 

            // Start the time-consuming operation.

            e.Result = ActualProcessIsHere(bw);

 

            // If the operation was canceled by the user,

            // set the DoWorkEventArgs.Cancel property to true.

            if (bw.CancellationPending)

            {

                e.Cancel = true;

            }

        }

 

        private int ActualProcessIsHere(BackgroundWorker bw)

        {

            for (int i = 0; i < 1000; i++)

            {

                if (bw.CancellationPending)

                    return 0;

 

                if (AddValue(1) == 100)

                    return 100;

 

                int delay = 11 - GetSpeed();

                System.Threading.Thread.Sleep(50 * delay);

            }

            return 1;

        }

 

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

        {

            if (e.Cancelled)

            {

                // The user canceled the operation.

                //MessageBox.Show("Operation was canceled");

                lblStatus.Text = "I stopped";

            }

            else if (e.Error != null)

            {

                // There was an error during the operation.

                lblStatus.Text = String.Format("An error occurred: {0}", e.Error.Message);

            }

            else if (e.Result.ToString() == "100")

            {

                //// The operation completed normally.

                CarRace f = (CarRace)this.MdiParent;

                f.whofinished += 1;

                lblStatus.Text = "I finished in " + f.whofinished.ToString() + " place!";

                if (f.whofinished == 1)

                    lblStatus.ForeColor = Color.Red;

            }

 

        }

 

        private int GetSpeed()

        {

            if (this.trackBar1.InvokeRequired)

            {

                GetSpeedCallBack b = new GetSpeedCallBack(GetSpeed);

                return (int)this.Invoke(b);

            }

            else

            {

                return trackBar1.Value;

            }

        }

 

        private void StartAgain()

        {

            if (this.progressBar1.InvokeRequired)

            {

                StartCallBack b = new StartCallBack(StartAgain);

                this.Invoke(b);

            }

            else

            {

                progressBar1.Value = 0;

            }

        }

 

        private int AddValue(int value)

        {

            if (this.progressBar1.InvokeRequired)

            {

                AddValueCallBack b = new AddValueCallBack(AddValue);

                return (int)this.Invoke(b, new object[] { value });

            }

            else

            {

                if (progressBar1.Value < progressBar1.Maximum - value)

                {

                    this.progressBar1.Value += value;

                    return 1;

                }

                else if (progressBar1.Value == progressBar1.Maximum - value)

                {

                    this.progressBar1.Value = progressBar1.Maximum;

                    return progressBar1.Maximum;

                }

                else

                {

                    return 0;

                }

            }

        }

 

        private void btnStop_Click(object sender, EventArgs e)

        {

            backgroundWorker1.CancelAsync();

        }

 

        private void btnReset_Click(object sender, EventArgs e)

        {

            if (!backgroundWorker1.IsBusy)

            {

                StartAgain();

            }

 

        }

 

        /// <summary>

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.IContainer components = null;

 

        /// <summary>

        /// Clean up any resources being used.

        /// </summary>

        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

        protected override void Dispose(bool disposing)

        {

            if (disposing && (components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }

 

        #region Windows Form Designer generated code

 

        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

            this.progressBar1 = new System.Windows.Forms.ProgressBar();

            this.btnStart = new System.Windows.Forms.Button();

            this.btnStop = new System.Windows.Forms.Button();

            this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();

            this.trackBar1 = new System.Windows.Forms.TrackBar();

            this.btnReset = new System.Windows.Forms.Button();

            this.lblStatus = new System.Windows.Forms.Label();

            this.lblSpeed = new System.Windows.Forms.Label();

            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();

            this.SuspendLayout();

            //

            // progressBar1

            //

            this.progressBar1.Location = new System.Drawing.Point(71, 13);

            this.progressBar1.Name = "progressBar1";

            this.progressBar1.Size = new System.Drawing.Size(484, 23);

            this.progressBar1.Step = 1;

            this.progressBar1.TabIndex = 0;

            this.progressBar1.Maximum = 100;

            //

            // btnStart

            //

            this.btnStart.Location = new System.Drawing.Point(74, 74);

            this.btnStart.Name = "btnStart";

            this.btnStart.Size = new System.Drawing.Size(75, 23);

            this.btnStart.TabIndex = 1;

            this.btnStart.Text = "Start";

            this.btnStart.UseVisualStyleBackColor = true;

            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);

            //

            // btnStop

            //

            this.btnStop.Location = new System.Drawing.Point(155, 74);

            this.btnStop.Name = "btnStop";

            this.btnStop.Size = new System.Drawing.Size(75, 23);

            this.btnStop.TabIndex = 2;

            this.btnStop.Text = "Stop";

            this.btnStop.UseVisualStyleBackColor = true;

            this.btnStop.Click += new System.EventHandler(this.btnStop_Click);

            //

            // backgroundWorker1

            //

            this.backgroundWorker1.WorkerReportsProgress = true;

            this.backgroundWorker1.WorkerSupportsCancellation = true;

            this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);

            this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);

            //

            // trackBar1

            //

            this.trackBar1.Location = new System.Drawing.Point(12, 17);

            this.trackBar1.Minimum = 1;

            this.trackBar1.Name = "trackBar1";

            this.trackBar1.Orientation = System.Windows.Forms.Orientation.Vertical;

            this.trackBar1.Size = new System.Drawing.Size(45, 80);

            this.trackBar1.TabIndex = 3;

            this.trackBar1.Value = 1;

            //

            // btnReset

            //

            this.btnReset.Location = new System.Drawing.Point(236, 74);

            this.btnReset.Name = "btnReset";

            this.btnReset.Size = new System.Drawing.Size(75, 23);

            this.btnReset.TabIndex = 4;

            this.btnReset.Text = "Reset";

            this.btnReset.UseVisualStyleBackColor = true;

            this.btnReset.Click += new System.EventHandler(this.btnReset_Click);

            //

            // lblStatus

            //

            this.lblStatus.AutoSize = true;

            this.lblStatus.Location = new System.Drawing.Point(71, 39);

            this.lblStatus.Name = "lblStatus";

            this.lblStatus.Size = new System.Drawing.Size(37, 13);

            this.lblStatus.TabIndex = 5;

            this.lblStatus.Text = "Status";

            //

            // lblSpeed

            //

            this.lblSpeed.AutoSize = true;

            this.lblSpeed.Location = new System.Drawing.Point(9, 1);

            this.lblSpeed.Name = "lblSpeed";

            this.lblSpeed.Size = new System.Drawing.Size(38, 13);

            this.lblSpeed.TabIndex = 6;

            this.lblSpeed.Text = "Speed";

            //

            // frmCar

            //

            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

            this.ClientSize = new System.Drawing.Size(567, 109);

            this.Controls.Add(this.lblSpeed);

            this.Controls.Add(this.lblStatus);

            this.Controls.Add(this.btnReset);

            this.Controls.Add(this.trackBar1);

            this.Controls.Add(this.btnStop);

            this.Controls.Add(this.btnStart);

            this.Controls.Add(this.progressBar1);

            this.Name = "frmCar";

            this.Text = "Car";

            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();

            this.ResumeLayout(false);

            this.PerformLayout();

 

        }

 

        #endregion

        private System.Windows.Forms.ProgressBar progressBar1;

        private System.Windows.Forms.Button btnStart;

        private System.Windows.Forms.Button btnStop;

        private System.ComponentModel.BackgroundWorker backgroundWorker1;

        private System.Windows.Forms.TrackBar trackBar1;

        private System.Windows.Forms.Button btnReset;

        private System.Windows.Forms.Label lblStatus;

        private System.Windows.Forms.Label lblSpeed;

 

        public frmCar()

        {

            InitializeComponent();

        }

    }

}