Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. ProgressBar in multi-threaded application

ProgressBar in multi-threaded application

Scheduled Pinned Locked Moved C#
csharpwinformshelptutorialquestion
14 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Lutoslaw

    How to report a calculations' progress using a ProgressBar in a WinForms multi-threaded application? I want to utilize CPUs as much as I can and so use all (four) cores. After some googling the only thing I found is a suggestion to use a BackgroudWorker, but it supports only one thread for the same work. The code looks like this:

    Parallel.For(0, width, delegate(int x)
    {
    //for (int x = 0; x < width; x++)
    //{
    //calculations with two more nested loops.
    (***)
    //}
    });

    At (***) I tried the following: 1.)

    progress.Value = x;

    This thrown an exception of course. 2.)

    progress.BeginInvoke(new Action (delegate {
    progress.Value = x;
    }));

    Here the ProgressBar was updated after all calculation were finished. Tried to set a number of threads to 3 but it didn't change anything. The implemetation of the Parallel class is robust imho. Any help appreciated.

    Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

    T Offline
    T Offline
    TheFM234
    wrote on last edited by
    #2

    There is a method that background workers have that is called "ReportProgress", and a event called "ProgressChanged" that triggers when the ReportProgress method is called. You can access the ProgressChanged from the original thread, unlike trying to directly access the progress bar via progressbar.value = x.

    1 Reply Last reply
    0
    • L Lutoslaw

      How to report a calculations' progress using a ProgressBar in a WinForms multi-threaded application? I want to utilize CPUs as much as I can and so use all (four) cores. After some googling the only thing I found is a suggestion to use a BackgroudWorker, but it supports only one thread for the same work. The code looks like this:

      Parallel.For(0, width, delegate(int x)
      {
      //for (int x = 0; x < width; x++)
      //{
      //calculations with two more nested loops.
      (***)
      //}
      });

      At (***) I tried the following: 1.)

      progress.Value = x;

      This thrown an exception of course. 2.)

      progress.BeginInvoke(new Action (delegate {
      progress.Value = x;
      }));

      Here the ProgressBar was updated after all calculation were finished. Tried to set a number of threads to 3 but it didn't change anything. The implemetation of the Parallel class is robust imho. Any help appreciated.

      Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

      L Offline
      L Offline
      leppie
      wrote on last edited by
      #3

      gajatko wrote:

      progress.BeginInvoke

      Do not use BeginInvoke, as that will queue the invocation. Invoke should be sufficient.

      xacc.ide - now with TabsToSpaces support
      IronScheme - 1.0 alpha 4a out now (29 May 2008)

      L 1 Reply Last reply
      0
      • L Lutoslaw

        How to report a calculations' progress using a ProgressBar in a WinForms multi-threaded application? I want to utilize CPUs as much as I can and so use all (four) cores. After some googling the only thing I found is a suggestion to use a BackgroudWorker, but it supports only one thread for the same work. The code looks like this:

        Parallel.For(0, width, delegate(int x)
        {
        //for (int x = 0; x < width; x++)
        //{
        //calculations with two more nested loops.
        (***)
        //}
        });

        At (***) I tried the following: 1.)

        progress.Value = x;

        This thrown an exception of course. 2.)

        progress.BeginInvoke(new Action (delegate {
        progress.Value = x;
        }));

        Here the ProgressBar was updated after all calculation were finished. Tried to set a number of threads to 3 but it didn't change anything. The implemetation of the Parallel class is robust imho. Any help appreciated.

        Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

        realJSOPR Offline
        realJSOPR Offline
        realJSOP
        wrote on last edited by
        #4

        You're making it harder than it has to be. Use a BackgroundWorker object to perform the calculation, and call the UpdateProgress method at the desired interval.

        private BackgroundWorker myWorker = BackgroundWorker();

        //--------------------------------------------------------------------------------
        /// /// Initializes the background worker thread.
        ///
        private void InitEncryptWorker()
        {
        myWorker.WorkerReportsProgress = true;
        myWorker.WorkerSupportsCancellation = true;
        myWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(myWorker_DoWork);
        myWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(myWorker_RunWorkerCompleted);
        myWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(myWorker_ProgressChanged);
        }

        //--------------------------------------------------------------------------------
        public void myWorker_DoWork(Object sender, DoWorkEventArgs e)
        {
        BackgroundWorker thisWorker = sender as BackgroundWorker;

        int progress = 0;
        for (int i = 0; i < 1000; i++)
        {
            if (!thisWork.CancellationPending)
            {
                // do some work here
        
                // and then report progress
                thisWorker.ReportProgress(progress);
            }
        }
        

        }

        //--------------------------------------------------------------------------------
        private void myWorker_ProgressChanged(object sender,ProgressChangedEventArgs e)
        {
        if (e.ProgressPercentage != this.progressBar.Value)
        {
        this.progressBar.Value = e.ProgressPercentage;
        }
        }

        //--------------------------------------------------------------------------------
        private void myWorker_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
        {
        }

        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
        -----
        "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

        L 1 Reply Last reply
        0
        • realJSOPR realJSOP

          You're making it harder than it has to be. Use a BackgroundWorker object to perform the calculation, and call the UpdateProgress method at the desired interval.

          private BackgroundWorker myWorker = BackgroundWorker();

          //--------------------------------------------------------------------------------
          /// /// Initializes the background worker thread.
          ///
          private void InitEncryptWorker()
          {
          myWorker.WorkerReportsProgress = true;
          myWorker.WorkerSupportsCancellation = true;
          myWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(myWorker_DoWork);
          myWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(myWorker_RunWorkerCompleted);
          myWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(myWorker_ProgressChanged);
          }

          //--------------------------------------------------------------------------------
          public void myWorker_DoWork(Object sender, DoWorkEventArgs e)
          {
          BackgroundWorker thisWorker = sender as BackgroundWorker;

          int progress = 0;
          for (int i = 0; i < 1000; i++)
          {
              if (!thisWork.CancellationPending)
              {
                  // do some work here
          
                  // and then report progress
                  thisWorker.ReportProgress(progress);
              }
          }
          

          }

          //--------------------------------------------------------------------------------
          private void myWorker_ProgressChanged(object sender,ProgressChangedEventArgs e)
          {
          if (e.ProgressPercentage != this.progressBar.Value)
          {
          this.progressBar.Value = e.ProgressPercentage;
          }
          }

          //--------------------------------------------------------------------------------
          private void myWorker_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
          {
          }

          "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
          -----
          "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

          L Offline
          L Offline
          Lutoslaw
          wrote on last edited by
          #5

          This way you use only one thread for calculations and utilize 25% of quad core processors

          Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

          realJSOPR 1 Reply Last reply
          0
          • L leppie

            gajatko wrote:

            progress.BeginInvoke

            Do not use BeginInvoke, as that will queue the invocation. Invoke should be sufficient.

            xacc.ide - now with TabsToSpaces support
            IronScheme - 1.0 alpha 4a out now (29 May 2008)

            L Offline
            L Offline
            Lutoslaw
            wrote on last edited by
            #6

            Application hangs when using Invoke instead of BeginInvoke. From debugger, it stops on call to the Invoke method.

            Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

            1 Reply Last reply
            0
            • L Lutoslaw

              How to report a calculations' progress using a ProgressBar in a WinForms multi-threaded application? I want to utilize CPUs as much as I can and so use all (four) cores. After some googling the only thing I found is a suggestion to use a BackgroudWorker, but it supports only one thread for the same work. The code looks like this:

              Parallel.For(0, width, delegate(int x)
              {
              //for (int x = 0; x < width; x++)
              //{
              //calculations with two more nested loops.
              (***)
              //}
              });

              At (***) I tried the following: 1.)

              progress.Value = x;

              This thrown an exception of course. 2.)

              progress.BeginInvoke(new Action (delegate {
              progress.Value = x;
              }));

              Here the ProgressBar was updated after all calculation were finished. Tried to set a number of threads to 3 but it didn't change anything. The implemetation of the Parallel class is robust imho. Any help appreciated.

              Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

              D Offline
              D Offline
              Daniel Grunwald
              wrote on last edited by
              #7

              Parallel.For does not run the calculation in the background. It just splits the work to multiple threads, but the UI is blocked until the calculation has finished. If you want multiple threads to calculate in the background, use BackgroundWorker+Parallel.For.

              L 2 Replies Last reply
              0
              • D Daniel Grunwald

                Parallel.For does not run the calculation in the background. It just splits the work to multiple threads, but the UI is blocked until the calculation has finished. If you want multiple threads to calculate in the background, use BackgroundWorker+Parallel.For.

                L Offline
                L Offline
                Lutoslaw
                wrote on last edited by
                #8

                Frankly speaking I use my own implementation of Parallel to preserve .Net 2.0 compatibility but it works as you said, too. I will check if it works and post soon.

                Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

                1 Reply Last reply
                0
                • L Lutoslaw

                  This way you use only one thread for calculations and utilize 25% of quad core processors

                  Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

                  realJSOPR Offline
                  realJSOPR Offline
                  realJSOP
                  wrote on last edited by
                  #9

                  C'mon, be a programmer. If your calculations take so long that it's bothersome, put some Thread.Sleep(10) calls in the loop somewhere.

                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                  -----
                  "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                  M L 2 Replies Last reply
                  0
                  • realJSOPR realJSOP

                    C'mon, be a programmer. If your calculations take so long that it's bothersome, put some Thread.Sleep(10) calls in the loop somewhere.

                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                    -----
                    "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                    M Offline
                    M Offline
                    Mark Salsbery
                    wrote on last edited by
                    #10

                    :-D

                    Mark Salsbery Microsoft MVP - Visual C++ :java:

                    1 Reply Last reply
                    0
                    • realJSOPR realJSOP

                      C'mon, be a programmer. If your calculations take so long that it's bothersome, put some Thread.Sleep(10) calls in the loop somewhere.

                      "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                      -----
                      "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                      L Offline
                      L Offline
                      Lutoslaw
                      wrote on last edited by
                      #11

                      John Simmons / outlaw programmer wrote:

                      C'mon, be a programmer

                      Yeach and then post your code on a Coding Horrors forum before someone else does. :laugh:

                      Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

                      realJSOPR 1 Reply Last reply
                      0
                      • D Daniel Grunwald

                        Parallel.For does not run the calculation in the background. It just splits the work to multiple threads, but the UI is blocked until the calculation has finished. If you want multiple threads to calculate in the background, use BackgroundWorker+Parallel.For.

                        L Offline
                        L Offline
                        Lutoslaw
                        wrote on last edited by
                        #12

                        BackgroundWorker+Parallel.For combination doesn't work.

                        progress.Value = e.ProgressPercentage;

                        throws an exception (Cross-thread operation not valid: Control 'progress' blah blah blah) and

                        progress.Invoke(new Action(delegate {
                        progress.Value = e.ProgressPercentage;
                        }));

                        hangs the program. Any ideas? I though that this situation is so common that there is at least one satisfactory solution for it... :(

                        Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

                        D 1 Reply Last reply
                        0
                        • L Lutoslaw

                          BackgroundWorker+Parallel.For combination doesn't work.

                          progress.Value = e.ProgressPercentage;

                          throws an exception (Cross-thread operation not valid: Control 'progress' blah blah blah) and

                          progress.Invoke(new Action(delegate {
                          progress.Value = e.ProgressPercentage;
                          }));

                          hangs the program. Any ideas? I though that this situation is so common that there is at least one satisfactory solution for it... :(

                          Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

                          D Offline
                          D Offline
                          Daniel Grunwald
                          wrote on last edited by
                          #13

                          Why is it hanging? Take a look at what the threads are doing. Why is the main thread blocked? What is it waiting for? Maybe you have a dead lock? (progress.Invoke waits for the main thread to finish any active event handlers, maybe the main thread is somehow still waiting for your calculation?)

                          1 Reply Last reply
                          0
                          • L Lutoslaw

                            John Simmons / outlaw programmer wrote:

                            C'mon, be a programmer

                            Yeach and then post your code on a Coding Horrors forum before someone else does. :laugh:

                            Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

                            realJSOPR Offline
                            realJSOPR Offline
                            realJSOP
                            wrote on last edited by
                            #14

                            Yeah, I'll do that. In the meantime, you'll still be dickin' around with your code, and I will have finished this particular task moved on to something else. On the other hand, maybe using 25% of the CPU ain't so bad, after all. Of course, we can't determine the trade-offs because you haven't given us all the requirements.

                            "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                            -----
                            "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups