Click here to Skip to main content
15,890,897 members
Articles / Programming Languages / C#
Article

ProgressDialog: for executing long-running code with some thread safety

Rate me:
Please Sign up or sign in to vote.
2.70/5 (9 votes)
23 May 2006CPOL2 min read 65.2K   892   45   14
A dialog for executing long-running code on a thread (written in C#).

Introduction

If your WinForms application needs to execute some long-running code, it's best to run it on a thread so the main thread of the form isn't hung up. It is also helpful if the form has a progress bar so the thread can let the user know how it's progressing. But this requires cross-thread access which needs to be done safely.

This brings up three points:

  1. The code for thread safety isn't that difficult, but why do have to write it for every form that needs a progress bar?
  2. The progress bar is only needed while the long-running code runs, so why have it on the form at all?
  3. What if the user wants to cancel the operation?

My solution is to use a dialog that encapsulates the thread-safe manipulation of the progress bar and allows any form to use it without having to add a progress bar and its code to the form itself.

The ability to cancel the operation depends on the operation, but is supported.

Using the code

The code for the ProgressDialog is in ProgressDialog.cs, the other files are for the example application.

Because I derived from the Form class, all the public methods and properties of Form are available, which is not really a good idea. I should have encapsulated the form inside my class, but I decided to be lazy. The result is that the user of the class can modify the appearance of the dialog, and maybe that's not such a bad thing, you have the source code anyway.

At any rate, the only parts of the class that I expect the user of the class to use are:

  • The constructors
  • The ShowDialog method
  • The Result property
  • The WasCancelled property
  • The RaiseUpdateProgress method
  • The ProgressDialogStart delegate

The example demonstrates all of these but the delegate:

C#
// This example demonstrates the ProgressDialog
//
// The form for this example contains
// only a Button, a NumericUpDown, and a Label
// Set the NumericUpDown (to a number of seconds to sleep)
// Click the Button
// When the process completes (or is canceled)
// set the Label to show the elapsed time

namespace Progger
{
    public partial class Form1 : System.Windows.Forms.Form
    {
        // Declare one -- in this example it's important to initialize it
        PIEBALD.Dialogs.ProgressDialog dlg = null ;

        public Form1 ()
        {
            InitializeComponent() ;
        }
        
        private void button1_Click ( object sender , System.EventArgs e )
        {
            System.DateTime start = System.DateTime.Now ;

            // Instantiate it (this example uses an anonymous method)
            dlg = new PIEBALD.Dialogs.ProgressDialog
            (
                "Sleeping",
                this.Icon,
                System.Windows.Forms.ProgressBarStyle.Blocks
// or                System.Windows.Forms.ProgressBarStyle.Marquee,
                true
// or               false,
                delegate
                (
                    object[] Params
                )
                {
                    int howlong = (int) Params [ 0 ] * 10 ;

                    // This is a simple way of implementing the cancel handling
                    for ( int runner = 0 ; !dlg.WasCancelled && 
                        ( runner < howlong ) ; runner++ )
                    {
                        System.Threading.Thread.Sleep ( 100 ) ;

                        // Need to update the ProgressBar
                        // when it's Block or Continuous style
                        // Use a calculation that's appropriate for your usage
                        dlg.RaiseUpdateProgress ( runner * 100 / howlong ) ;
                    }

                    // Return what you want
                    return ( System.DateTime.Now ) ;
                },
                // This value will be passed to the method
                (int) this.numericUpDown1.Value
            ) ;

            // Then all you need to do is 
            dlg.ShowDialog() ;

            // Afterward you can access the WasCancelled
            // and Result properties as needed
            this.label1.Text = string.Format
            (
                "{0} {1:0.00} seconds",
                dlg.WasCancelled?"Woken after":"Slept for",
                ( (System.DateTime) dlg.Result - start ).TotalSeconds
            ) ;
        }
    }
}

Points of Interest

Things to learn from this: cross-thread safety, delegates, and anonymous methods.

History

  • First posted - 2006-05-18.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
BSCS 1992 Wentworth Institute of Technology

Originally from the Boston (MA) area. Lived in SoCal for a while. Now in the Phoenix (AZ) area.

OpenVMS enthusiast, ISO 8601 evangelist, photographer, opinionated SOB, acknowledged pedant and contrarian

---------------

"I would be looking for better tekkies, too. Yours are broken." -- Paul Pedant

"Using fewer technologies is better than using more." -- Rico Mariani

"Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’" -- Steve McConnell

"Every time you write a comment, you should grimace and feel the failure of your ability of expression." -- Unknown

"If you need help knowing what to think, let me know and I'll tell you." -- Jeffrey Snover [MSFT]

"Typing is no substitute for thinking." -- R.W. Hamming

"I find it appalling that you can become a programmer with less training than it takes to become a plumber." -- Bjarne Stroustrup

ZagNut’s Law: Arrogance is inversely proportional to ability.

"Well blow me sideways with a plastic marionette. I've just learned something new - and if I could award you a 100 for that post I would. Way to go you keyboard lovegod you." -- Pete O'Hanlon

"linq'ish" sounds like "inept" in German -- Andreas Gieriet

"Things would be different if I ran the zoo." -- Dr. Seuss

"Wrong is evil, and it must be defeated." –- Jeff Ello

"A good designer must rely on experience, on precise, logical thinking, and on pedantic exactness." -- Nigel Shaw

“It’s always easier to do it the hard way.” -- Blackhart

“If Unix wasn’t so bad that you can’t give it away, Bill Gates would never have succeeded in selling Windows.” -- Blackhart

"Use vertical and horizontal whitespace generously. Generally, all binary operators except '.' and '->' should be separated from their operands by blanks."

"Omit needless local variables." -- Strunk... had he taught programming

Comments and Discussions

 
Questionwhy i got a error like this? Pin
bailuotuo15-Nov-07 16:01
bailuotuo15-Nov-07 16:01 
AnswerRe: why i got a error like this? Pin
PIEBALDconsult15-Nov-07 16:36
mvePIEBALDconsult15-Nov-07 16:36 
Generalgetting errors Pin
gayeeee4-Dec-06 9:30
gayeeee4-Dec-06 9:30 
GeneralRe: getting errors Pin
PIEBALDconsult4-Dec-06 14:49
mvePIEBALDconsult4-Dec-06 14:49 
GeneralBetter way.. Pin
scanner77723-Oct-06 7:01
scanner77723-Oct-06 7:01 
GeneralRe: Better way.. Pin
PIEBALDconsult24-Oct-06 7:27
mvePIEBALDconsult24-Oct-06 7:27 
Questionslow? Pin
a_takavci17-Sep-06 22:08
a_takavci17-Sep-06 22:08 
AnswerRe: slow? Pin
PIEBALDconsult18-Sep-06 7:59
mvePIEBALDconsult18-Sep-06 7:59 
GeneralRe: slow? Pin
a_takavci19-Sep-06 3:19
a_takavci19-Sep-06 3:19 
GeneralRe: slow? Pin
PIEBALDconsult21-Sep-06 11:51
mvePIEBALDconsult21-Sep-06 11:51 
GeneralRe: slow? Pin
a_takavci23-Sep-06 12:32
a_takavci23-Sep-06 12:32 
General.Style only available in .NET 2.0 Pin
drdre200519-Aug-06 6:38
drdre200519-Aug-06 6:38 
GeneralPIEBALD (unavailable) Pin
TassosK20-May-06 5:11
TassosK20-May-06 5:11 
GeneralRe: PIEBALD (unavailable) Pin
PIEBALDconsult20-May-06 6:01
mvePIEBALDconsult20-May-06 6:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.