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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T19:35:42+00:00 2026-05-25T19:35:42+00:00

I’m building a Windows Service using System.Timers.Timer . The tasks computed by the Timer’s

  • 0

I’m building a Windows Service using System.Timers.Timer. The tasks computed by the Timer’s delegate can take from several seconds to several minutes. I would like to make sure that, when the service is stopped, all delegated threads currently running complete before being disposed.

Here is the code, however it does not do what I expect, as currently running threads never complete if the Windows Service is stopped while they are running.

public abstract class AgentServiceBase : ServiceBase
{
    private System.ComponentModel.IContainer components = null;
    private System.Timers.Timer _Timer;
    private string _logPath;
    private const int MAXNUMBEROFTHREADS = 10;
    protected int interval = 25000;
    protected int numberOfAllowedThreads = 2;

    public AgentServiceBase()
    {
        this.InitializeComponent();
        this._logPath = (Path.GetDirectoryName(Assembly.GetAssembly(this.GetType()).CodeBase)).Substring(6).Replace("/", @"\");
    }

    protected override void OnStart(string[] args)
    {
        if (args.Length > 0)
        {
            int.TryParse(args[0], out interval);
        }

        if (args.Length > 1)
        {
            int.TryParse(args[1], out numberOfAllowedThreads);
            if (numberOfAllowedThreads > MAXNUMBEROFTHREADS)
            {
                numberOfAllowedThreads = MAXNUMBEROFTHREADS;
            }
            if (numberOfAllowedThreads == 1)
            {
                numberOfAllowedThreads = 2;
            }
        }

        ThreadPool.SetMaxThreads(numberOfAllowedThreads, numberOfAllowedThreads);

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

    }

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

        Process currentProcess = Process.GetCurrentProcess();

        foreach (Thread t in currentProcess.Threads)
        {
            t.Join();
        }

    }
    /// <summary>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    private void InitializeComponent()
    {
        components = new System.ComponentModel.Container();
        this.ServiceName = "Agent Service - Johnhenry";

    }

    private void PollWrapper(object sender, ElapsedEventArgs e)
    {
        try
        {
            this.Poll(sender, e);
        }
        catch (Exception exception)
        {
            string message = this.GetType().FullName + "  - Windows Service Exception\n";
            message += exception.GetNestedExceptionInSingleStringOutput();

            FileHelper.Log(message, this._logPath, "exception", FileHelper.LogFileNameChangeFrequency.DAYLY);
        }
    }

    protected abstract void Poll(object sender, ElapsedEventArgs e);
}

Many thanks,

Giuseppe

UPDATE:

After few different attempts with counting the current process’s own threads I eventually settled with a simpler solution which is using a counter of the threads the timer had initiated and are still running. Based on that I call the Sleep on the main thread and issue a RequestAdditionalTime until all threads have ended.
Following the revised 2 methods:

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

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

    }



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

        try
        {
            this.Poll(sender, e);
        }
        catch (Exception exception)
        {
            string message = this.GetType().FullName + "  - Windows Service Exception\n";
            message += exception.GetNestedExceptionInSingleStringOutput();

            FileHelper.Log(message, this._logPath, "exception", FileHelper.LogFileNameChangeFrequency.DAYLY);
        }
        finally
        {
            numberOfRunningThreads--;
        }
    }
  • 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-25T19:35:43+00:00Added an answer on May 25, 2026 at 7:35 pm

    You can achieve that by calling RequestAdditionalTime as long as your threads haven’t finished the work yet in your implementation of OnStop inside the loop (before and/or after the call to Join()).

    BUT BEWARE that Windows can get impatient and decide to kill your Windows Service – for example during shutdown…

    For more information see the MSDN reference at http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.aspx

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

Sidebar

Related Questions

Does anyone know how can I replace this 2 symbol below from the string
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
That's pretty much it. I'm using Nokogiri to scrape a web page what has
Seemingly simple, but I cannot find anything relevant on the web. What is the
this is what i have right now Drawing an RSS feed into the php,
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I have a French site that I want to parse, but am running into

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.