Home > Back-end >  Thread counter reading greater than zero after all threads have completed
Thread counter reading greater than zero after all threads have completed

Time:03-08

I have a thread counter on my program and it should hit 0 when all my threads have completed. I started by having threads at the beginning of my worker and threads-- at the end but my counter was reading 145 after all threads completed. So I put them right next to each other as shown below and it still is not reading 0, now it reads 8 after all threads have completed. How is this even possible? I am saving data from about 13000 mail messages to a sql server database. Each message calls ProcessMailMessage once.

        int threads = 0;

        public bool ProcessMailMessage(byte[] mymsg, string username, string folder)
        {
            BackgroundWorker bg = new BackgroundWorker();

            bg.DoWork  = (sss, res) => {
                
                threads  ;
                threads--;
               // save some data to database

            };

            bg.RunWorkerAsync();

            return true;
        }

CodePudding user response:

I have resolved this by incrementing the counter before calling RunWorkerAsync() and decrementing in the RunWorkerComplete event

            bg.RunWorkerCompleted  = (s, res) =>
            {
                threads--;
            };

            threads  ;
            bg.RunWorkerAsync();

  • Related