Click here to Skip to main content
15,867,704 members
Articles / Desktop Programming / WPF

WPF ProgressBar

Rate me:
Please Sign up or sign in to vote.
4.66/5 (52 votes)
28 Jul 2009CPOL2 min read 343.9K   17K   68   35
This is a simple example of how to use a ProgressBar in WPF.

Introduction

This article demonstrates how to use a WPF ProgressBar in a "tight code loop".

Background

For years, progress bars have been very useful and very easy to use in regular Windows Forms applications. All that was necessary was to set the Minimum and Maximum properties, then incrementally modify the Value property to report the progress. When necessary, DoEvents() was inserted to allow the form to refresh and update the progress bar.

WPF progress bars are conceptually the same as Windows progress bars; however, a very noticeable difference is that using standard coding techniques, the WPF Progress Bars do not update correctly while the application is processing. This creates a very undesirable effect, especially since the whole purpose of the progress bar is to... report the progress.

There are many situations where "tight loops" are required in code, such as when data is being read from a file. A standard coding approach is to open the file, then loop through the entire file, reading either lines, characters, or bytes in each pass. A progress bar may be used to report the progress of this operation.

Tight loops present a bit of a challenge for WPF progress bars, and the standard coding techniques do not produce the same results as they do in Windows Forms. Therefore, this article specifically addresses this issue, and demonstrates how to use a WPF ProgressBar in a "tight code loop".

Using the code

The WPF ProgressBar has a "SetValue" method that can be used to update the progress of the ProgressBar. However, this method will not cause the ProgresssBar to refresh when there is a tight coding loop. Therefore, it is necessary to use the Invoke method of the Dispatcher class to update the progress of the ProgressBar and cause it to refresh correctly on the form.

The Dispatcher class provides services for managing the queue of work items for a thread.

One of the arguments of the Dispatcher.Invoke method is a delegate. Since a delegate can be created and used to point to a specific method to invoke, we will create and use one that will point to the ProgressBar's SetValue method, so it will have the exact same signature as well.

Here's the complete example in Visual Basic and C#:

Visual Basic:

VB
'Create a Delegate that matches
'the Signature of the ProgressBar's SetValue method
Private Delegate Sub UpdateProgressBarDelegate(ByVal dp As _
                 System.Windows.DependencyProperty, _
                 ByVal value As Object)

Private Sub Process()

    'Configure the ProgressBar
    ProgressBar1.Minimum = 0
    ProgressBar1.Maximum = Short.MaxValue
    ProgressBar1.Value = 0

    'Stores the value of the ProgressBar
    Dim value As Double = 0

    'Create a new instance of our ProgressBar Delegate that points
    ' to the ProgressBar's SetValue method.
    Dim updatePbDelegate As New _
        UpdateProgressBarDelegate(AddressOf ProgressBar1.SetValue)

    'Tight Loop: Loop until the ProgressBar.Value reaches the max
    Do Until ProgressBar1.Value = ProgressBar1.Maximum

         value += 1

        'Update the Value of the ProgressBar:
        ' 1) Pass the "updatePbDelegate" delegate
        '    that points to the ProgressBar1.SetValue method
        ' 2) Set the DispatcherPriority to "Background"
        ' 3) Pass an Object() Array containing the property
        '    to update (ProgressBar.ValueProperty) and the new value
        Dispatcher.Invoke(updatePbDelegate, _
            System.Windows.Threading.DispatcherPriority.Background, _
            New Object() {ProgressBar.ValueProperty, value})

    Loop

End Sub

C#

C#
//Create a Delegate that matches 
//the Signature of the ProgressBar's SetValue method
private delegate void UpdateProgressBarDelegate(
        System.Windows.DependencyProperty dp, Object value);


private void Process()
{
    //Configure the ProgressBar
    ProgressBar1.Minimum = 0;
    ProgressBar1.Maximum = short.MaxValue;
    ProgressBar1.Value = 0;

    //Stores the value of the ProgressBar
    double value = 0;

    //Create a new instance of our ProgressBar Delegate that points
    // to the ProgressBar's SetValue method.
    UpdateProgressBarDelegate updatePbDelegate = 
        new UpdateProgressBarDelegate(ProgressBar1.SetValue);

    //Tight Loop: Loop until the ProgressBar.Value reaches the max
    do
    {
        value += 1;

        /*Update the Value of the ProgressBar:
            1) Pass the "updatePbDelegate" delegate
               that points to the ProgressBar1.SetValue method
            2) Set the DispatcherPriority to "Background"
            3) Pass an Object() Array containing the property
               to update (ProgressBar.ValueProperty) and the new value */
        Dispatcher.Invoke(updatePbDelegate, 
            System.Windows.Threading.DispatcherPriority.Background, 
            new object[] { ProgressBar.ValueProperty, value });
    }
    while (ProgressBar1.Value != ProgressBar1.Maximum);
}

Conclusion

This is a very brief, and hopefully clear and concise article on using a WPF ProgressBar. The source code for both Visual Basic and C# is included for you as a reference.

I hope it's helpful to you!

License

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


Written By
Software Developer DataPrint, LLC
United States United States

Comments and Discussions

 
QuestionHelped a lot Pin
jay nyanja6-Jun-14 10:55
jay nyanja6-Jun-14 10:55 
GeneralGreat Pin
Vasuldracek12-Nov-13 8:35
Vasuldracek12-Nov-13 8:35 
QuestionYou're a good man! Pin
Yovav6-Nov-13 8:00
Yovav6-Nov-13 8:00 
GeneralThanks for for a simple demonstration Pin
timboabobo6-Nov-13 5:55
timboabobo6-Nov-13 5:55 
QuestionMy Vote of 5 Pin
tcm121115-Jun-12 1:01
tcm121115-Jun-12 1:01 
GeneralMy vote of 5 Pin
penguindude30-Jan-12 6:53
penguindude30-Jan-12 6:53 
QuestionA good article Pin
BorisL200025-Dec-11 14:44
BorisL200025-Dec-11 14:44 
A good article for WPF beginers. Thank you
QuestionA BackgroundWorker is the the way to go Pin
rhyous26-Aug-11 13:44
rhyous26-Aug-11 13:44 
GeneralMy vote of 1 PinPopular
Ian Shlasko5-Jul-11 9:57
Ian Shlasko5-Jul-11 9:57 
GeneralMy vote of 5 Pin
strogos14-Feb-11 12:17
strogos14-Feb-11 12:17 
Generalgreat applicatin Pin
dcakmak28-Sep-10 9:20
dcakmak28-Sep-10 9:20 
GeneralThanks Pin
all2neat_12-Aug-10 10:49
all2neat_12-Aug-10 10:49 
GeneralRe: Thanks Pin
CS Rocks12-Aug-10 11:57
CS Rocks12-Aug-10 11:57 
GeneralMy vote of 5 Pin
Daniel Schopf4-Aug-10 1:44
Daniel Schopf4-Aug-10 1:44 
GeneralAwesome example Pin
Rich33-Apr-10 18:31
Rich33-Apr-10 18:31 
GeneralThanks Pin
Nigel Stratton19-Aug-09 11:27
Nigel Stratton19-Aug-09 11:27 
GeneralRe: Thanks Pin
CS Rocks19-Aug-09 11:30
CS Rocks19-Aug-09 11:30 
GeneralOne tiny note... Pin
IT-Konkret16-Aug-09 23:42
IT-Konkret16-Aug-09 23:42 
GeneralRe: One tiny note... Pin
anunrao24-Aug-09 20:23
anunrao24-Aug-09 20:23 
GeneralNice article Pin
Rodrigo Lourenço7-Aug-09 7:02
Rodrigo Lourenço7-Aug-09 7:02 
GeneralMy vote of 1 Pin
Member 35967587-Aug-09 0:33
Member 35967587-Aug-09 0:33 
GeneralI think the reason for bad responses was... Pin
Peter Row4-Aug-09 21:59
Peter Row4-Aug-09 21:59 
GeneralAnother solution Pin
FantasticFiasco4-Aug-09 4:14
FantasticFiasco4-Aug-09 4:14 
GeneralThanks for the feedback! [modified] Pin
CS Rocks3-Aug-09 5:05
CS Rocks3-Aug-09 5:05 
GeneralRe: Thanks for the feedback! Pin
Cristian Amarie20-Sep-09 5:17
Cristian Amarie20-Sep-09 5:17 

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.