On starting a windows service, start threading. How can I accomplish this?

21,311

There should be no infinite while loop in the service OnStart method. That method should complete as soon as possible. Use it to setup the service threads/tasks but not to do anything that will block indefinitely.

Without any exception handling, thread pools, etc., here is how I used to do it (last time I wrote such a threaded service, which was 5 years ago, so no apologies if it is dated. Nowadays I try to use Task Parallel lib), NOTE to readers: I am simply demonstrating the idea, and snagged this from an old project. If you can do better, feel free to edit to improve this answer, or add your own answer.

public partial class GyrasoftMessagingService : ServiceBase
{

  protected override void OnStart(string[] args)
  {
     ThreadStart start = new ThreadStart(FaxWorker); // FaxWorker is where the work gets done
     Thread faxWorkerThread = new Thread(start);

     // set flag to indicate worker thread is active
     serviceStarted = true;

     // start threads
     faxWorkerThread.Start();
  }

  protected override void OnStop()
  {
     serviceStarted = false;
     // wait for threads to stop
     faxWorkerThread.Join(60);

     try
     {
        string error = "";
        Messaging.SMS.SendSMSTextAsync("5555555555", "Messaging Service stopped on " + System.Net.Dns.GetHostName(), ref error);
     }
     catch
     {
        // yes eat exception if text failed
     }
  }

  private static void FaxWorker()
  {
     // loop, poll and do work
  }


}
Share:
21,311
Nation
Author by

Nation

Software Engineer | Business Solutions/Technology Advisor | Full Stack Web Developer | .NET & other Microsoft Technologies | Embedded Systems C#, Javascript, CSS, HTML, Embedded C/C++ .Net, AngularJS, NodeJS, Ionic Senior Software Developer, Agile & Scrum Coach @MC Systems Lead Software Developer, Payment Solutions & Services Division @MC Systems Working on a @commuting startup “The gift of mental power comes from God, Divine Being, and if we concetrate our minds on that truth, we become in tune with this great power. My Mother had taught me to seek all truth in the Bible.” Tesla Helping others to build Amazing Things!

Updated on September 08, 2020

Comments

  • Nation
    Nation over 3 years

    I am creating a window service, but when it starts I want it create threads to keep pool/monitor of a ftp site. The issue I am facing, is when I try starting the service with a while(true){} inside which check for new files and then it should ThreadPool.QueueUserWorkItem, the service has a timeout issue when starting.