Welcome to WindowsClient.net | My Blog | Sign in | Join

Windows Client Videos

How Do I: Build an Asynchronous Progress Bar in WPF

A progress bar is a standard user interface control used to indicate the progress of tasks that take time to complete. If other events block (or take time to release) an application's UI thread, the progress bar cannot be updated, thereby defeating its intended use. In this video, Todd Miranda shows how to update the UI from a separate thread.

Author: Todd Miranda

Posted: Sep 03 2008, 09:40 PM by jytylr | with 12 comment(s)
Filed under:

Comments

subhasisrout said:

well explained.......

# September 9, 2008 3:42 PM

brado said:

Couple questions:

What is the difference between new Thread/Dispatcher and BackgroundWorker?

Does it make any difference to use x:Name versus just Name for a WPF UIElement?

# September 13, 2008 10:39 AM

tmiranda said:

brado,

  Let me see if this makes sense:  Because the work you do with UI elements has to occur on the thread that owns that element (the UI thread), you cannot act upon that element from another thread.  Using the dispatcher, you can inject an action into the UI thread processing (messaging loop).  Using the new thread/dispatcher has been around for a while in one form or another.  The BackgroundWorker class was introduced in 2.0.  It can be a simpler way of doing the same thing.  When you use the BackgroundWorker, the dispatcher is being used behind the scenes.  I would not say that BackgroundWorker wraps the dispatcher, but through its use of various SynchronizationContext classes, the dispatcher is invoked to synchronize activity between threads.  Hopefully that at least gives you and idea of the difference.  I simply chose to use the dispatcher directly because I thought it would be good to understand what is really going on.  Using the BackgroundWorker hides some of that.

As far as the difference between x:Name and Name: there is not a practical difference between the two.  Keep in mind that some elements do not have a Name property, thus the need for the creation of the markup extension x:Name.  I would suggest always using x:Name for consistency.  Otherwise, you have Name in some places and x:Name in others.

Todd

# September 18, 2008 5:32 PM

brado said:

Thanks Todd, both things makes sense.

# September 25, 2008 12:56 PM

throwback45 said:

I created an xbap and I'm using the following loop to get the values out of my textboxes:

Dim ctrl as Control

For Each ctrl In Me.ControlArea.Children...

I get an exception when this hits the Border control:

System.InvalidCastException was unhandled by user code

 Message="Unable to cast object of type 'System.Windows.Controls.Border' to type 'System.Windows.Controls.Control'."

 Source="WPF_RM"

 StackTrace:

      at WPF_RM.Page1.LoopAllTextBoxes() in C:\WebProjects\RM_Ribbon\WPF_RM\Page1.xaml.vb:line 100

      at WPF_RM.Page1.DocSearch_Executed(Object sender, RoutedEventArgs e) in C:\WebProjects\RM_Ribbon\WPF_RM\Page1.xaml.vb:line 38

      at WPF_RM.Page1.OnEnterButton(Object sender, KeyEventArgs e) in C:\WebProjects\RM_Ribbon\WPF_RM\Page1.xaml.vb:line 139

      at System.Windows.Input.KeyEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)

      at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)

      at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)

      at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)

      at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)

      at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)

      at System.Windows.Input.InputManager.ProcessStagingArea()

      at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)

      at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)

      at System.Windows.Interop.HwndKeyboardInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawKeyboardActions actions, Int32 scanCode, Boolean isExtendedKey, Boolean isSystemKey, Int32 virtualKey)

      at System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction(MSG& msg, Boolean& handled)

      at System.Windows.Interop.HwndKeyboardInputProvider.FilterMessage(IntPtr hwnd, Int32 message, IntPtr wParam, IntPtr lParam, Boolean& handled)

      at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

      at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

      at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)

      at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)

      at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)

      at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)

      at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)

      at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)

      at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)

      at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)

      at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)

      at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)

      at System.Windows.Threading.Dispatcher.Run()

      at System.Windows.Application.RunDispatcher(Object ignore)

      at System.Windows.Application.StartDispatcherInBrowser(Object unused)

 InnerException:

Any advice?

# March 4, 2009 5:04 PM

tmiranda said:

throwback,

  I am not sure what the purpose of looping through all the controls is but I might suggest trying declaring ctrl to be of type UIElement.  That might do what you want.  The root of the problem is that border is not a control. Border is a decorator element and does not contain control in its inheritance chain.

Todd

# March 7, 2009 12:17 PM

TroubleSum said:

Hello, I have just tried your example but am gettings a problem with this line of code :

           Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { prgExcel.SetValue(ProgressBar.ValueProperty, 1.0); }, null);.

The error is : ProgressBar does not contain a definition for ValueProperty.

There is no ValuePropery in the intelisense of the ProgressBar,  what am i missing here??

Many Thanks in Advance

# May 11, 2009 4:15 AM

TroubleSum said:

Hey, I have sorted it out, i had a custom control in my project called ProgressBar so i was referancing that an not the wpf control haha. oh well atleast its sorted :)

Regards

# May 11, 2009 6:55 AM

tmiranda said:

I am glad you figured it out TroubleSum!  Sorry for the delay getting back to you.

Todd

# May 14, 2009 10:35 AM

jbaurle said:

Great article!

Here you find another nice article about how to implement a WPF progress dialog:

www.parago.de/.../how-to-implement-a-modern-progress-dialog-for-wpf-applications

# June 18, 2011 9:07 AM

modugenics said:

This is good article but I still have a troubles implementing asynchronous calls.

This example use Thread.Sleep() that are nothing to deal with your application... while I try to do is save a file (convert something in bytes and writing into a File) so all is in 100% related main thread and get this Exception System.UnauthorizedAccessException: Invalid cross-thread access error as the video show that can be solved with Dispatcher... but we came back to the same point => create a thread, in the tread call dispatcher,... is like synchronous, no???

Any Idea, how to solve this problem??????????

# August 5, 2011 9:21 PM

Rhyous said:

I have a post that is similar with a bit of an MVVM focus.

<a href="www.rhyous.com/.../">A Progress Bar using WPF’s ProgressBar Control, BackgroundWorker, and MVVM</a>

# August 26, 2011 7:59 PM