Sie sind auf Seite 1von 14

9/28/2017 Show progress dialog during long process – C# | Per Schlüter

Per Schlüter
My snippet library

Show progress dialog during long process – C#


Like 15

If you execute a time-consuming operation, it can


cause your user interface to seem it has stopped
responding even if it hasn’t.
With the BackgroundWorker class  you can run an
operation on a separate, dedicated thread. 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


Click to enlarge
that report the progress of your operation and
signal when your operation is ៯�nished.

Download (read license)


Source code

Create a new Windows Form Application.


The main form, Form1, is automatically created. So add another form to the project and name it
“AlertForm”. (Right-click on your project and select Add > Windows Form)

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.

Double-click on the button to create a Click event.


Visual Studio will switch over to code view, and this is where we will write our code.

Add the following code to the Click event:

http://perschluter.com/show­progress­dialog­during­long­process­c­sharp/ 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; } 
}

The complete code should look something like this now:

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/show­progress­dialog­during­long­process­c­sharp/ 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/show­progress­dialog­during­long­process­c­sharp/ 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;

Add the following code to the buttonStart_Click event

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.

So lets write the buttonCancel_Click event.

// 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/show­progress­dialog­during­long­process­c­sharp/ 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); 
    } 
}

When we call BackgroundWorker.ReportProgress, the backgroundworker will run ProcessChanged event.


So lets add some code to it.
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;

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/show­progress­dialog­during­long­process­c­sharp/ 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/] .

34 thoughts on “Show progress dialog during long process – C#”

Philip Regenie
January 4, 2013 at 8:46 pm

I think you did an excellent job making this program and writing it up. Thanks.

Per Schlüter Post author

January 5, 2013 at 1:06 pm

I hope this was helpful to you.

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/show­progress­dialog­during­long­process­c­sharp/ 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

Awesome!  Great How2!

Sundar
August 16, 2014 at 6:49 am

http://perschluter.com/show­progress­dialog­during­long­process­c­sharp/ 7/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter

Awesome code and explanation. Thanks.

Carlos
September 16, 2014 at 12:01 am

It was exactly what I need! thanks very much.

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?

Per Schlüter Post author

December 4, 2014 at 5:14 pm

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/show­progress­dialog­during­long­process­c­sharp/ 8/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter

December 9, 2014 at 7:42 pm

So gre8!!!

thanks for your clear explain

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:

In the post you have


private void cancelAsyncButton_Click(object sender, EventArgs e)

But in the source code, there is:


private void buttonCancel_Click(object sender, EventArgs e).

This of course brings a problem with the line (of the post)

alert.Canceled += new EventHandler<EventArgs>(buttonCancel_Click);

Because buttonCancel_Click does not exist…

http://perschluter.com/show­progress­dialog­during­long­process­c­sharp/ 9/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter

Per Schlüter Post author

May 22, 2015 at 11:05 am

Thanks for the input.


I will take a look at it.

TimO
June 23, 2015 at 10:51 pm

Very helpful , I am closer to really understanding progress bars an asynchronous workers.

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.

i am using C# with VS2013.

Per Schlüter Post author

October 20, 2015 at 2:13 pm

Hello Jawad,
Look at backgroundWorker1_DoWork() method in my example ៯�le.
There you ៯�nd this “dummy” code

http://perschluter.com/show­progress­dialog­during­long­process­c­sharp/ 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!!

I have a question though!!

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. 

Am I doing something wrong?

Per Schlüter Post author

http://perschluter.com/show­progress­dialog­during­long­process­c­sharp/ 11/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter

November 13, 2015 at 11:32 am

Check what values you have in your variables, i and listA.Count.


The code you posted should work if you have the correct values.

Je៛�
December 1, 2015 at 10:47 pm

Where is the backgroundWorker1 declared?

Per Schlüter Post author

December 2, 2015 at 12:07 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~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Thank you so much.

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/show­progress­dialog­during­long­process­c­sharp/ 12/14
9/28/2017 Show progress dialog during long process – C# | Per Schlüter

Per Schlüter Post author

June 22, 2016 at 10:49 am

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

Dear Per Schlüter

Can you share to me  and all people , your souce, Thanks so much

Per Schlüter Post author

June 27, 2016 at 9:08 am

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/show­progress­dialog­during­long­process­c­sharp/ 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#?

Per Schlüter Post author

August 8, 2017 at 12:03 pm

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/show­progress­dialog­during­long­process­c­sharp/ 14/14

Das könnte Ihnen auch gefallen