backgroundWorker Code Example for Cancel Button in C#

In C#, backgroundWorker object is used to make program cancellation without blocking UI. In here, we will make Code Example for Cancel Button in C#. In your windows forms application, use backgroundWorker object.

backgroundworker

Once when backgroundWorker component is added to your project, adjust its properties:

WorkerReportsProgress – True
WorkerSupportsCancellation – True

backgroundworker-properties

We can add now one start button, one cancel button, one progress bar and two labels, to show progress of our application execution. We also need to use namespace

using System.Threading;

Now, we are adding one public method for displaying message and one public int variable that will have sum of first 100 integer numbers.

public void display(string text)
{

MessageBox.Show(text);

}
public int Sum = 0;

Now, we can simulate some work with the following method:

public void simulateWork()
{

Thread.Sleep(100);

}

Three methods native to backgroundWorker control we should add are:
_DoWork, _ProgressChanged, _RunWorkerCompleted

_DoWork must not have GUI component method. This method actually does main job.

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// There should be no GUI component method
for (int i = 1; i < 101; i++)
{

// set cancelation to pending. Execute cancelation.

if (backgroundWorker1.CancellationPending)

{

e.Cancel = true;

}

else

{

simulateWork();

backgroundWorker1.ReportProgress(i);

Sum += i;

}

}
}

_ProgressChanged is updated from _DoWork method. Its where GUI component are updated.

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{

// This is updated from DoWork method. Its where GUI component are updated

progressBar1.Value = e.ProgressPercentage;

label1.Text = e.ProgressPercentage.ToString() + ” %”;

label2.Text = Sum.ToString();

}

And _RunWorkerCompleted is called when operation in background is over! Can also accept GUI components.

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{

// Called when operation in background is over! Can also accept GUI components

if (e.Cancelled)

{

display(“Not completed”);

}

else

{

display(“Work is successfully done”);

}

}

private void cmdStart_Click(object sender, EventArgs e)
{

backgroundWorker1.RunWorkerAsync();

}

And in cancel button we place this code:

private void btnCancel_Click(object sender, EventArgs e)
{

backgroundWorker1.CancelAsync();

}

And, of course, all methods in background worker shod be attached in the code as follows:

public Form1()
{

InitializeComponent();

backgroundWorker1 = new BackgroundWorker();

backgroundWorker1.WorkerReportsProgress = true;

backgroundWorker1.WorkerSupportsCancellation = true;

backgroundWorker1.DoWork += backgroundWorker1_DoWork;

backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;

backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;

}

 

External links:

backgroundWorker Code Example for Cancel Button in C# in Microsoft

Posted in c-sharp-code-examples Tagged with: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*