How to show progress of ProgressBar

Hello.

I increment ProgressBar.Value, but it shows only 100%.

for( int idx = 0; idx <= 100; idx += 10 ) {
progressBar.Value = idx;
System.Threading.Thread.Sleep( 100 ); // Some operations
}

Why this ProgressBar does not show 10%, 20%, ...



Answer this question

How to show progress of ProgressBar

  • Gavin Joyce

    As Valentin said, it's because you're blocking the UI thread. If you've done any work with WinForms and threading the concepts are similiar however in the world of WPF rendering is actually done on a separate thread so until the UI thread returns the instructions cannot be propagated to the rendering thread and therefore your UI does not update.

    Here's the link to the BackgroundWorker class which is probably the simplest solution to this problem. It's the same exact class that is used for WinForms, so... if you've used it there there's no diff. using it with WPF.

    HTH,
    Drew


  • KoKoNassar

    hYam,

    I can't answer if there is a way to force a visual update, but keep in mind the code you suggest is similar to a loop that constantly calls Application.DoEvents(). Though you can do it, it's never recommended. You are essentially blocking the input / dispatch thread and only allowing updates however fast you can go through your loop.

    Also worth noting is that your Thread.Sleep(100) effectively says that UpdateRender could only be called 10 times per second max. (assuming other code in your loop doesn't consume even more time). In essence, you have effectively capped the rendering engine at 10 FPS, which is far less then the 100+ FPS that's possible on current hardware.


  • PetePark

    Thank you for your reply.
    I will try to use BackgroundWorker.

    But, in some cases, it may be difficult to use BackgroundWorker.
    I hope I can use some method to update rendering directly.
    For example...
    for( int idx = 0; idx <= 100; idx += 10 ) {
    progressBar.Value = idx;
    Dispatcher.UpdateRender(); // Update rendering
    System.Threading.Thread.Sleep( 100 ); // Some operations
    }


  • Dah_Live

    It's because you are blocking the UI thread - any modification of the UI happens after the method exits. Depending on what you're trying to do, you can use a timer or a background worker.


  • Uttam Kr. Dhar

    I can think of a few things. First off, what is your ranage on the progress bar If it is 0.0 to 1.0, then anything 1.0 or greater will just show 100% (ProgressBar.Value is a System.Double in case you didn't notice).

    The other thing I notice is that you are calling Thread.Sleep. You may be keeping WPF from performing it's updates. I would suggest you try moving that code into a Timer_Tick handler.


  • How to show progress of ProgressBar