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 8406353
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T23:05:16+00:00 2026-06-09T23:05:16+00:00

I’m building a multi-thread windows service. I’m having a little difficulty figuring out the

  • 0

I’m building a multi-thread windows service. I’m having a little difficulty figuring out the best way to cleanly stop the service once all the threads have run through. The code is below. I have looked at ManualResetEvent, CountdownEvent and using Interlocked. I’m not sure which one would best suit my implementation.

Thanks for the assistance.

    private bool _isExiting;
    private bool IsExiting //if this is set to true exit but wait for all threads
    {
        get { return _isExiting; }
        set
        {
            _isExiting = value;
            if (value)
                Stop();
        }
    }
   private JobProfiler profiler;

   protected override void OnStart(string[] args)
    {
        try
        {
            profiler = new Profiler(MaxThreads);
            ThreadPool.QueueUserWorkItem(DoWork); // main thread set up thread for work
        }
        catch (Exception ex)
        {
            LogError(ex);
            Stop();
        }
    }

    protected void DoWork(object data)
    {
        while (!IsExiting)
        {
            try
            {
                profiler.RunProfiles(profiles); //this should wait until all child threads are done
                Thread.Sleep(ThreadSleep); //sleep before next iteration
            }
            catch (Exception ex)
            {
                LogError(ex);
                errorCount++;

                if (errorCount > 10)  //if 10 serious errors happen stop the service
                {
                    IsExiting = true;
                    break;
                }
            }
        }
    }

    protected override void OnStop()
    {
        try
        {

            if(profiler != null)
                profiler.IsExiting = true; //setting a variable here to signal all remaining threads to stop

            //here it should be waiting for the main and child threads to finish

            base.OnStop();
        }
        catch
        {
            base.OnStop();
        }
    }


    //profiler class
    //******************************************************

    private readonly Semaphore _throttle;   //setting up a throttle for the number of threads we will allow to execute at once

    public void RunProfiles(List<Profiles> profiles)
    {
        foreach (var profile in profiles)
        {
            if (IsExiting) break; //if an exit command is called stop iterating

            _throttle.WaitOne(); // Wait on a semaphore slot to become available
            ThreadPool.QueueUserWorkItem(RunProfile, profile ); //then add to thread queue

        }
    }

    private void RunProfile(object profile)
    {
        try
        {
            var p = (profile as Profile);

            if (p == null || IsExiting)
            {
                _throttle.Release(); // Release the semaphore slot if profile not found or if we're exiting
                return;
            }

            //****
            //do a bunch of stuff
            //****

            _throttle.Release(); // Release the semaphore slot

        }
        catch (Exception ex)
        {
            log.Error(ex);
            _throttle.Release(); // Release the semaphore slot
        }

    }
  • 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-06-09T23:05:17+00:00Added an answer on June 9, 2026 at 11:05 pm

    I would use Tasks (TPL from .NET 4.0) and use CancellationToken to cancel tasks if Stop event occurs or some exception and you want to stop the service.

    But if you want to stick to the semaphore or older synchronization primitives your solution will work just fine.

    Also check out this article(s): Threading

    There are several useful examples in there that may help you to pick the best solution. I believe CountdownEvent is highly optimized and OS independent, so from your list, I would pick that one.

    • 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
We're building an app, our first using Rails 3, and we're having to build
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
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.