Windows service does not start fully

I made this small Windows service in C #, and I believe that maybe something is wrong with my ThreadPool code, which completely disables my Windows service. If you know, a Windows service seems to work just fine when it looks at the services console, it still claims to be "starting up". When I restarted my server, the service seemed to stop again, although I set it to start automatically.

Check out my code below:

protected override void OnStart(string[] args)
{
     int itemCount = itemList.Count;

     this.doneEvents = new ManualResetEvent[itemCount];
     for (int i = 0; i < itemCount; i++)
     {
         int oId = this.itemList[i];
         this.doneEvents[i] = new ManualResetEvent(false);

         ThreadPool.QueueUserWorkItem(data =>
         {
             while (this.activated)
             {
                 DateTime start = DateTime.Now;

                 // my code here

                 // choke point
                 TimeSpan duration = (DateTime.Now - start);
                 if (duration.Milliseconds < CONST_WAITMILLISECONDS)
                    Thread.Sleep((CONST_WAITMILLISECONDS - duration.Milliseconds));
              }

              this.doneEvents[i].Set(); // thread done

            }, oId);
         }

         WaitHandle.WaitAll(doneEvents);

}
+3
source share
2 answers

I think you could wrap the logic inside OnStartin a thread. This thread will be closed when you receive the event OnStop.

Something like that:

Thread _ServiceThread;
protected override void OnStart(string[] args) { 
    _ServiceThread = new Thread(() => { /* your current OnStart logic here...*/ });
    _ServiceThread.Start();
}
protected override void OnStop() {
    _ServiceThread.Stop();
}
+2
source

OnStart WaitHandle.WaitAll(doneEvents);. Windows , - WaitAll.

OnStart , , Windows .

+3

All Articles