Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6639293
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T23:32:12+00:00 2026-05-25T23:32:12+00:00

I’m building a Windows Service base class to manages the polling off a schedule’s

  • 0

I’m building a Windows Service base class to manages the polling off a schedule’s table of any pending task and the running them.

The Windows service is using the System.Timers.Timer to start the schedule’s table polling.

I’m setting the ThreadPool.SetMaxThread to 10 before initialising the timer.

    protected override void OnStart(string[] args)
    {
        ThreadPool.SetMaxThreads(10, 10);

        this._Timer = new System.Timers.Timer();
        this._Timer.Elapsed += new ElapsedEventHandler(PollWrapper);
        this._Timer.Interval = 100;
        this._Timer.Enabled = true;
    }

The delegate method called by the timer keeps the count of the running threads so that it can be used in the OnStop() method to wait for each thread to complete before disposing the service.

    private void PollWrapper(object sender, ElapsedEventArgs e)
    {
        numberOfRunningThreads++;

        try
        {
            this.Poll(sender, e);
        }
        catch (Exception exception)
        {
            //some error logging here
        }
        finally
        {
            numberOfRunningThreads--;
        }
    }




    protected override void OnStop()
    {
        this._Timer.Enabled = false;

        while (numberOfRunningThreads > 0)
        {
            this.RequestAdditionalTime(1000);
            Thread.Sleep(1000);
        }
    }

Often, the service would not stop when I try to stop it from the Windows service management console. If I debug it and add a breakpoint to the OnStop() method I can see that it is not because the numberOfRunningThreads is stuck on a number greater than 0 (often much greater than 10!). No tasks are running and it stays on that number forever!

Firstly, I don’t understand how that number could ever be greater than 10, despite the ThreadPool.SetMaxThreads should limit it to 10?

Secondly, even if I did not set the maximum number of threads, I would expect the finally block of the PollWrapper’s to eventually bring the count back to 0. If the counter stays greater than 0, it can be explained only with the finally block not executing, right!? How that is possible?

And lastly, would you suggest a differently way to limit the Poll to a number of possible concurrent running threads to a fixed number (.NET 3.5)?

Many thanks.

UPDATE:

After reading Yahia’s comments on reentrancy and SetMaxThread I have modified the PollWrapper so that it should always limit the max number of spawned running threads. I will still to make sure Poll is reentrant.

private void PollWrapper(object sender, ElapsedEventArgs e)
        {
            lock(this)
            {
                if(this.numberOfRunningThreads < this.numberOfAllowedThreads)
                {
                    this.numberOfRunningThreads++;

                    Thread t = new Thread(
                        () =>
                        {
                            try
                            {
                                this.Poll(sender, e);
                            }
                            catch (Exception ex)
                            { 
                                //log exception
                            }
                            finally
                            {
                                Interlocked.Decrement(ref this.numberOfRunningThreads);
                            }
                        }
                    );
                    t.Start();
                }
            }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T23:32:13+00:00Added an answer on May 25, 2026 at 11:32 pm

    As per request of OP (see comments above) in regards to the updated question/code:

    The lock statement behaves like a “critical” section i.e. it stops that specific code block from being executed in parallel – the parameter of lock is used as the “syncrhonization object” so that any code block surrounded by a lock on the same variable wouldn’t be executed in parallel on a different thread.

    The lock statement doesn’t do anything with the variable/its contents – for example it doesn’t “freeze” the contents so they can still be change anywhere anytime in any executing code (parallel) as long as that code is not protected by lock and the same variable as a parameter.

    If you look at the link I provided (your points to an outdated documentation version for VS2003) it says explicitely that lock(this) for example is NOT ok to use – the reason and a best practice is described accordingly…

    ALL of the above renders the provided code (updated version) still not thread-safe (although definitively better than the original version).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I am currently running into a problem where an element is coming back from
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.