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.Threading;
namespace BackgroundWorkerSample
{
public partial class CalculateAddForm : Form
{
protected BackgroundWorker backgroundWorker1 = new BackgroundWorker();
//private int numberToCompute = 0;
//private int highestPercentageReached = 0;
public CalculateAddForm()
{
InitializeComponent();
InitializeBackgoundWorker();
}
// Set up the BackgroundWorker object by
// attaching event handlers.
private void InitializeBackgoundWorker()
{
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
private long ComputeAdd(int n, BackgroundWorker worker, DoWorkEventArgs e)
{
long result = 0;
// Abort the operation if the user has canceled.
// Note that a call to CancelAsync may have set
// CancellationPending to true just after the
// last invocation of this method exits, so this
// code will not have the opportunity to set the
// DoWorkEventArgs.Cancel flag to true. This means
// that RunWorkerCompletedEventArgs.Cancelled will
// not be set to true in your RunWorkerCompleted
// event handler. This is a race condition.
for (int i = 1; i <= n; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
else
{
result += i;
Thread.Sleep(100);
// Report progress as a percentage of the total task.
int percentComplete = (int)((float)i / (float)n * 100);
worker.ReportProgress(percentComplete);