Documente Academic
Documente Profesional
Documente Cultură
Per Schlüter
My snippet library
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 1/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
// 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);
Later we will add the EventHandler to Form1, this is because that if the user clicks on the Cancel button, we
want to handle the event in Form1 where our BackgroundWorker is running.
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; }
}
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;
namespace BackgroundWorkerDemo
{
public partial class AlertForm : Form
{
#region PROPERTIES
public string Message
{
set { labelMessage.Text = value; }
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 2/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
}
public int ProgressValue
{
set { progressBar1.Value = value; }
}
#endregion
#region METHODS
public AlertForm()
{
InitializeComponent();
}
#endregion
#region EVENTS
public event EventHandler<EventArgs> Canceled;
private void buttonCancel_Click(object sender, EventArgs e)
{
// Create a copy of the event to work with
EventHandler<EventArgs> ea = Canceled;
/* If there are no subscribers, eh will be null so we need to check
* to avoid a NullReferenceException. */
if (ea != null)
ea(this, e);
}
#endregion
}
}
Now we are done with the AlertForm, so switch over to Form1 or whatever you have renamed it to.
Add one button and one label to the form, rename the button to buttonStart and the label to labelResult.
Double-click on the button to create the Click event. Go back to design view as we don’t want to add code to
the event at this time.
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 �ash) 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).
Now we have done all that we need in design view, so lets stay in code view until we are done.
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 3/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
Scroll up to the beginning and add a �eld 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();
}
Here we create an instance of the AlertForm and assigns the event handler to get the event that are raised
if the user clicks on Cancel in the AlertForm. Opens the AlertForm and starts the backgroundworker.
// 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();
}
}
If the user clicks on Cancel, the backgroundworker will cancel and the AlertForm window will close.
Now we have to add code to the three event we added for the backgroundworker.
Lets start with the DoWork event. This is where you will do your time-consuming work. Deleting �les,
downloading �les, or what it is that you want to do.
In this example we just runs a loop and make it sleep a while so it will take some time to �nish it.
We also pass a value to BackgroundWorker.ReportProgress() that will be passed to the label and
progressbar that we have in AlertForm.
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 4/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
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);
}
}
// 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;
Now we only have the RunWorkerCompleted event left, so 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 �nally we close the AlertForm window.
if (e.Cancelled == true)
{
labelResult.Text = "Canceled!";
}
else if (e.Error != null)
{
labelResult.Text = "Error: " + e.Error.Message;
}
else
{
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 5/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
labelResult.Text = "Done!";
}
// Close the AlertForm
alert.Close();
That’s it!
Now we have form with a progressbar that opens when our time-consuming process starts. And it will be
closed when the process are �nished or the users cancel the process.
This entry was posted in C# and tagged BackgroundWorker, C#, Progress dialog, ProgressBar on July 19,
2012 [http://perschluter.com/show-progress-dialog-during-long-process-c-sharp/] .
Philip Regenie
January 4, 2013 at 8:46 pm
I think you did an excellent job making this program and writing it up. Thanks.
Archie
September 10, 2013 at 5:21 am
* I like this post, useful and will bene�t a lot of programmer who will come across this.
* I’ll to put all these code together, it’s good thing that this is done in a decent oop approach.
* I’m quite working in a fast pace environment, I hope that there’s a downloadable working app of this.
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 6/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
Angel
November 15, 2013 at 9:02 pm
Thanks dude!!!
Puja
November 21, 2013 at 8:59 am
Great Article + nice post + Source code. Thanks you safe my time
Bill
December 18, 2013 at 7:01 pm
Intermediate user (engineer, not programmer), �rst time using backgroundworkers. Very helpful, thanks,
Bill
Michael Evenson
March 26, 2014 at 1:14 pm
This was great – you should be a teacher if you are not already. Great instructions.
AmridgeJack
April 30, 2014 at 5:33 pm
Sundar
August 16, 2014 at 6:49 am
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 7/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
Carlos
September 16, 2014 at 12:01 am
Victor Nguyen
October 9, 2014 at 5:15 pm
THANKS. Very useful information and help. Very easy to follow and integrate.
Hieu
December 4, 2014 at 2:01 pm
If you change alert.Show() into alert.ShowDialog(), it does not work. How can I �x this issue?
Hi Hieu,
You should be able to get it to work with ShowDialog if you rebuilt it with an delegate that you invoke.
But the simplest way should be to set the alert to always be on top. ( I know, this is not the same as
ShowDialog. But maybe it is enough?)
alert.TopMost = true;
Hamid
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 8/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
So gre8!!!
David
April 21, 2015 at 9:20 pm
Thanks for this post! and to make it look like the progress form is a dialog, you can disabled the main form
before showing the progress form. And then enable the main form again on
backgroundWorker1_RunWorkerCompleted:
alert = new AlertForm();
this.Enabled = false;
alert.Show();
Rafael
May 21, 2015 at 5:25 pm
Hello. I believe you have a di៛�erence between the source code you provided and the one on this post:
This of course brings a problem with the line (of the post)
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 9/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
TimO
June 23, 2015 at 10:51 pm
Jawad Zaidi
October 17, 2015 at 10:46 am
Hi
I am new in this �led and need your kind help. i created a procedure that returns true on successful
completion, in which get data from database, working on it and write in data tables and �nally write this
data into an excel work sheet, as you know its time consuming process. how can i manage this process with
background worker and how can integrated with text box and progress bar.
Hello Jawad,
Look at backgroundWorker1_DoWork() method in my example �le.
There you �nd this “dummy” code
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 10/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
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);
}
}
This is the code that you should replace with your own, time consuming, code.
JJ Loots
October 7, 2016 at 9:28 pm
I agree with Jawad. I also can not get this right if I am writing data from table to Excel.
Ram
November 13, 2015 at 1:07 am
Nice article!!
In my program if I use worker.ReportProgress(i * 10); progress bar shows progress but if I use something
like worker.ReportProgress((i / listA.Count) * 100); progress bar doesn’t show any progress. It stuck at 0% and
at the end it generates the report for me.
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 11/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
Je៛�
December 1, 2015 at 10:47 pm
I didn’t declare it in the code, I dropped it on the form from the toolbox
aaa
January 13, 2016 at 7:18 am
Awesome~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pingback: Implementing backgroundworker to display progress bar in another form - HTML CODE
Dana Groulx
June 21, 2016 at 9:40 pm
there is no value called “Canceled” for the line EventHandler<EventArgs> ea = Canceled; Did you create a
variable called Canceled and I am missing that part of the code?
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 12/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
Canceled is declared in Alert.cs and it is an EventHandler that I copie just to work with.
Then the actual cancel event is handled in GUI.cs where I check the events from buttonCancel in Alert.cs.
// This event handler cancels the backgroundworker, fired from Cancel button in AlertForm.
private void buttonCancel_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
// Cancel the asynchronous operation.
backgroundWorker1.CancelAsync();
// Close the AlertForm
alert.Close();
}
}
Kevin
June 27, 2016 at 6:39 am
Can you share to me and all people , your souce, Thanks so much
In the top of the post you �nd a link to download the source code. Or click here: Source code
Brian Cook
December 15, 2016 at 3:55 pm
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 13/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter
Sir, thank you for the post. It helped a lot to understand the BGWorker example and the progress bar.
If I have two or more tasks in the BGWorker going, how would I display a second or third, etc. progress bar
for each?
Thanks,
Herve Nkurikiyimfura
August 6, 2017 at 3:54 pm
Can you please make an article on How to show the progress bar while connecting to a webClient server in
C#?
Hi,
I don’t think that you are able to calculate the time for connecting to a WebClient, so the only option I can
think of is to set the progressbar to repeating.
http://perschluter.com/showprogressdialogduringlongprocesscsharp/ 14/14