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
{
publicpartialclassForm1 : Form
{
BackgroundWorker BackWorker;
public Form1()
{
InitializeComponent();
BackWorker = newBackgroundWorker();
BackWorker.DoWork += newDoWorkEventHandler(backgroundWorker1_DoWork);
BackWorker.ProgressChanged += newProgressChangedEventHandler
(backgroundWorker1_ProgressChanged);
BackWorker.RunWorkerCompleted += newRunWorkerCompletedEventHandler
(backgroundWorker1_RunWorkerCompleted);
BackWorker.WorkerReportsProgress = true;
BackWorker.WorkerSupportsCancellation = true;
}
privatevoid backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = "Processing......" + progressBar1.Value.ToString() + "%";
}
privatevoid backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
label1.Text = "Task Cancelled.";
}
elseif (e.Error != null)
{
label1.Text = "Error while performing background operation.";
}
else
{
label1.Text = "Task Completed...";
}
button1.Enabled = true;
button2.Enabled = false;
}
privatevoid 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);
}
privatevoid button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
BackWorker.RunWorkerAsync();
}
privatevoid button2_Click(object sender, EventArgs e)
{
if (BackWorker.IsBusy)
{
BackWorker.CancelAsync();
}
}
}
}
See also:
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
Leave Comment