Home > DeveloperSection > Articles > Multithreading with the BackgroundWorker Component in ASP .NET

Multithreading with the BackgroundWorker Component in ASP .NET


C# C#  .NET  Thread  Threading  Thread Abort 
Ratings:
0 Comment(s)
 995  View(s)
Rate this:

Multithreading with the BackgroundWorker Component in ASP .NET

This article demonstrate, how to create a multithreaded application without being overhead by the complexity that comes with threading.

When we are developing Windows Forms applications in .NET Framework, you always notice that the user interface will freeze when your application is doing a time consuming operation. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running.

 The BackgroundWorker class allows you to run an operation on a separate, dedicated thread when you want a responsive UI and you are facing long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

 

To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished. You can create the BackgroundWorker in the Windows Forms Designer, it will appear in the Component Tray, and its properties will be displayed in the Properties window.

 

To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.

 

If your background operation requires a parameter, call RunWorkerAsync with your parameter. Inside the DoWork event handler, you can extract the parameter from the DoWorkEventArgs.Argument property.

 Example:

The following example demonstrates the basics of the BackgroundWorker class for executing a time-consuming operation asynchronously. The following illustration shows an example of the output.


In above example we want to create a Windows Forms application. Add a 
Label control that display processing percentage and add two Button controls named start Download and Cancel. Create Click event handlers for both buttons. From the Components tab of the Toolbox, add a BackgroundWorker component named backgroundWorker1. Create DoWork, ProgressChanged, by using its property.

 RunWorkerCompleted event handlers for the BackgroundWorker. In the code for the form, replace the existing code with the following code.

using System;

using System.ComponentModel;

using System.Threading;

using System.Windows.Forms;

namespace WorkerDemo

{

    public partial class Form1 : Form

    {

         BackgroundWorker BackWorker;

        public Form1()

        {

            InitializeComponent();

            BackWorker = new BackgroundWorker();

            BackWorker.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);

            BackWorker.ProgressChanged += new ProgressChangedEventHandler

                    (backgroundWorker1_ProgressChanged);

            BackWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler

                    (backgroundWorker1_RunWorkerCompleted);

            BackWorker.WorkerReportsProgress = true;

            BackWorker.WorkerSupportsCancellation = true;

        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)

        {

 

            progressBar1.Value = e.ProgressPercentage;

            label1.Text = "Processing......" + progressBar1.Value.ToString() + "%";

        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

        {

            if (e.Cancelled)

            {

                label1.Text = "Task Cancelled.";

            }

            else if (e.Error != null)

            {

                label1.Text = "Error while performing background operation.";

 

            }

            else

            {

                label1.Text = "Task Completed...";

            }

            button1.Enabled = true;

            button2.Enabled = false;

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

        {

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

            {

                Thread.Sleep(100);

                BackWorker.ReportProgress(i);

                if (BackWorker.CancellationPending)

                {

                    e.Cancel = true;

                    BackWorker.ReportProgress(0);

                    return;

                }

                else

                {

                    Thread.Sleep(1000);

                }

            }

            BackWorker.ReportProgress(100);

        }

        private void button1_Click(object sender, EventArgs e)

        {

 

            button1.Enabled = false;

            button2.Enabled = true;

            BackWorker.RunWorkerAsync();

        }

 

        private void button2_Click(object sender, EventArgs e)

        {

            if (BackWorker.IsBusy)

            {

                BackWorker.CancelAsync();

            }

        }

        }

}

 

See also:

·         Multithreading in C#

·         https://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

·         https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.95).aspx

 

 

 


Don't want to miss updates? Please click the below button!

Follow MindStick