By perschluter.com
If you execute a time-consuming operation, it can cause your user interface to seem it has stopped responding even if it hasn’t.
When you have time-consuming operations you can use the BackgroundWorker class to show a alert form, displaying that your application is in progress. Create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished.
Create a new Windows Form Application.
The main form, Form1, is automatically created. So add another form to the project and name it “AlertForm”.
Add a label to the form, change the name to labelMessage.
Add a progressbar.
Add a button, change the name to buttonCancel and change the text to Cancel.
Add the following code to the Click event:
// Create a copy of the event to work with
EventHandler<EventArgs> ea = Canceled;
/* If there are no subscribers, ea will be null so we need to check
* to avoid a NullReferenceException. */
if (ea != null)
ea(this, e);
We need to create two properties so we can update the label text and the
progressbar from Form1, so add the following properties:
public string Message
{
set { labelMessage.Text = value; }
}
public int ProgressValue
{
set { progressBar1.Value = value; }
}
Add one button and one label to the form, rename the button to buttonStart and the label to labelResult.
Add a BackgroundWorker to the form. In the properties window, change
WorkerReportsProgress and WorkerSupportsCancellation to true.
In the properties window, click on events button (the yellow flash) and you will see that the backgroundworker has three events. We will use them all, so double-click on all of them. (After creating an event you have to go back to design view to create the next).
In the properties window, click on events button (the yellow flash) and you will see that the backgroundworker has three events. We will use them all, so double-click on all of them. (After creating an event you have to go back to design view to create the next).
Scroll up to the beginning and add a field that will be used when we declare the AlertForm.
AlertForm alert;
if (backgroundWorker1.IsBusy != true)
{
// create a new instance of the alert form
alert = new AlertForm();
// event handler for the Cancel button in AlertForm
alert.Canceled += new EventHandler<EventArgs>(buttonCancel_Click);
alert.Show();
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
Opens the AlertForm and starts the backgroundworker.
write the buttonCancel_Click event.
If the user clicks on Cancel, the backgroundworker will cancel and the AlertForm window will close.
// This event handler cancels the backgroundworker, fired from Cancel button in AlertForm.
private void cancelAsyncButton_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
// Cancel the asynchronous operation.
backgroundWorker1.CancelAsync();
// Close the AlertForm
alert.Close();
}
}
add code to the three event we added for the backgroundworker.
start with the DoWork event.
This is where you will do your time-consuming work. Deleting files, downloading files, or what it is that you want to do.
This is where you will do your time-consuming work. Deleting files, downloading files, or what it is that you want to do.
We also pass a value to BackgroundWorker.ReportProgress() that will be
passed to the label and progressbar that we have in AlertForm.
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
worker.ReportProgress(i * 10);
System.Threading.Thread.Sleep(500);
}
}
When we call BackgroundWorker.ReportProgress, the backgroundworker will run ProcessChanged event.
We change the text on the label in our main form, and we pass values over to the label and progressbar in AlertForm.
// Show the progress in main form (GUI)
labelResult.Text = (e.ProgressPercentage.ToString() + "%");
// Pass the progress to AlertForm label and progressbar
alert.Message = "In progress, please wait... " + e.ProgressPercentage.ToString() + "%";
alert.ProgressValue = e.ProgressPercentage;
the RunWorkerCompleted event
lets add code that changes our label text to Canceled if the user
cancels, Done when it is completed or shows an error message if
something went wrong.
And finally we close the AlertForm window.
And finally we close the AlertForm window.
if (e.Cancelled == true)
{
labelResult.Text = "Canceled!";
}
else if (e.Error != null)
{
labelResult.Text = "Error: " + e.Error.Message;
}
else
{
labelResult.Text = "Done!";
}
// Close the AlertForm
alert.Close();