Sunday, March 4, 2018

Use Thread in Windows service for Long running function



There are some situations where we require to run a long running process “onstart” of windows service, so if you don't handle this scenrio properly it might give you an Error 1053: The service did not respond to the start or control request in a timely fashion.






So here is code, in this code snippet I ran a thread at “OnStart” method of service which internally calling method “MessageWorker” which will going to run in the background and it will not stuck at some point.

public partial class MessagingService : ServiceBase
{

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

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

     // start threads
     msgWorkerThread.Start();
  }

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

     try
     {
     // write some logic here

     }
     catch
     {
        // yes eat exception if text failed
     }
  }

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

Thanks for reading, please comment below if you have any idea to make this code better so that others can be benefited by this.

Happy Coding J