Nation Nation - 2 months ago 22
C# Question

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

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.

Answer

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
  }


}
Comments