Monday, July 14, 2014

  1. How to Use Dispatcher in WPF to Build Responsive Applications


  2. http://www.beingdeveloper.com/use-dispatcher-in-wpf-to-build-responsive-applications/


  1. private void Button_Click_2(object sender, RoutedEventArgs e)
  2. {
  3.     // Start a stop watch to count the execution time
  4.     var stopWatch = Stopwatch.StartNew();
  5.     lstItems.Items.Clear();
  6.     // Define and start a new thread to add 20000 items to the list box
  7.     ThreadStart job = new ThreadStart(() =>
  8.     {
  9.         for (int i = 0; i < 20000; i++)
  10.         {
  11.             // The new thread puts UI operations in the dispatching queue
  12.             Dispatcher.Invoke(DispatcherPriority.Normalnew Action(() =>
  13.             {
  14.                 lstItems.Items.Add("Stock Item " + i);
  15.             }));
  16.         }
  17.         stopWatch.Stop();
  18.         //! I cannot access WPF objects that is on the UI thread like this:
  19.         // lblTime.Content = "Finished in " + (double)stopWatch.ElapsedMilliseconds / 1000 + " seconds";
  20.         // I have to use the Dispatcher class as a mediator to queue the UI operation
  21.         Dispatcher.Invoke(DispatcherPriority.Normalnew Action(() =>
  22.         {
  23.             lblTime.Content = "Finished in " + (double)stopWatch.ElapsedMilliseconds / 1000 + " seconds";
  24.         }));
  25.     });
  26.     Thread thread = new Thread(job);
  27.     thread.Start();
  28. }

No comments:

Post a Comment