When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "BackgroundWorkerExample" and then click OK
Step 2: Design your form as below

Step 3: Add a click event handler to the button
struct DataParameter
{
public int Process;
public int Delay;
}
private DataParameter _inputparameter;
//Update progress bar
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progress.Value = e.ProgressPercentage;
lblPercent.Text = string.Format("Processing...{0}%", e.ProgressPercentage);
progress.Update();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//Set parameter
int process = ((DataParameter)e.Argument).Process;
int delay = ((DataParameter)e.Argument).Delay;
int index = 1;
try
{
for (int i = 0; i < process; i++)
{
if (!backgroundWorker.CancellationPending)
{
backgroundWorker.ReportProgress(index++ * 100 / process, string.Format("Process data {0}", i));
Thread.Sleep(delay);//used to simulate length of operation
//Add your code here...
}
}
}
catch (Exception ex)
{
backgroundWorker.CancelAsync();
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Process has been completed.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//Run backgroundworker
private void btnStart_Click(object sender, EventArgs e)
{
if (!backgroundWorker.IsBusy)
{
_inputparameter.Delay = 10;
_inputparameter.Process = 1200;
backgroundWorker.RunWorkerAsync(_inputparameter);
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (backgroundWorker.IsBusy)
backgroundWorker.CancelAsync();
}
VIDEO TUTORIALS