1

I am adding a progress bar for my WPF application. I want to show the real-time progress on the progress bar along with the count of generated files in real time like 4/100 files generated etc. Below are the two actions and the Tasks that are executing these actions

     Action Generate = new Action(() =>
            {
                foreach (string file in Files)
                {                  

            //all the logic to generate files


                    using (var streamWriter = new StreamWriter(newFileName, false, Encoding.Default))
                    {
                        foreach (string segment in newFile)
                        {
                            streamWriter.WriteLine(segment);
                        }
                        filesGenerated++;  

                //I need to do the second action here                    
                    }

                }
            });


   Action ShowProgressBar = new Action(() =>
            {
                progressBar.Value = filesGenerated 
  lblProgress.Content = filesGenerated + " File(s) Generated."; 

            });

   Task GenerateTask = Task.Factory.StartNew(() => Generate());

   Task ShowProgressBarTask = new Task(ShowProgressBar);

I have tried to nest the tasks but it is not working. What should I be doing to show real-time progress in progress bar.

San
  • 1,797
  • 7
  • 32
  • 56
  • Please use the Extended WPF Toolkit, it has the BusyIndicator element: [Codeplex project](http://wpftoolkit.codeplex.com/) [BusyIndicator documentation](http://wpftoolkit.codeplex.com/wikipage?title=BusyIndicator&referringTitle=Home) – Rumplin Aug 17 '11 at 12:43
  • Linking to a third party component doesn't really help to solve a code problem. You don't need the toolkit to show progress! – Dan Puzey Aug 17 '11 at 12:45
  • It's the same as Silverlight Toolkit, an essential part of building Silverlight application as is this WPF Toolkit... – Rumplin Aug 17 '11 at 12:59

3 Answers3

3
  1. Run your file creation code in another thread

  2. Set the value of progress bar in foreach loop by using Dispatcher cause you on another thread and can not change UI control from that one.

Basically you done.

Tigran
  • 61,654
  • 8
  • 86
  • 123
0

Take a look at my answers on the BackgroundWorker here and here.

Essentially, you will be moving the file creation to another thread, and reporting progress back in the UI thread, using the methods and events of the BackgroundWorker.

Community
  • 1
  • 1
Wonko the Sane
  • 10,623
  • 8
  • 67
  • 92
-1
public static class Refresh 

    {
        public static void Refresh_Controls(this UIElement uiElement)
        {
            uiElement.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { }));
        }
    }

In your main code:

Refresh.Refresh_Controls(progressBar1);