VB.NET - Code in the OnStart method of Windows Service executes continously

Asked By Parag Satpute on 14-Nov-13 05:08 AM
I have developed a Windows Service in VB.NET 2008 which is doing the following on start,

  1. Executing an application (.exe file)
  2. Creating a scheduled task with Windows Task Scheduler for running a batch file at scheduled time

I am able to accomplish the above but, when the service starts it creates multiple instances of the application it has executed and continues to create until the system freezes and i have to reboot it.
I tried a workaround by letting the service check registry key value and if the value is valid then execute the code else do not execute. But, even after this check there is no change. The service still continues to create multiple instances of the application and system freezes and lastly i have to reboot it.

Please let me know what needs to be done to overcome such situation.
Robbe Morris replied to Parag Satpute on 14-Nov-13 08:47 AM
I suspect the mistake you are making is attempting to run your logic on the same thread as the service and trigger it in the OnStart event.  Instead, you'll want to create a new background thread to run your logic.  In the sample below, all of my logic is in a separate class that can be instantiated.  It gets fired as a background thread.

using System.Threading;

protected override void OnStart(string[] args)
   var thread = new Thread(new ThreadStart(OnExecute));
   thread.IsBackground = true;

void OnExecute()
   var service = new MyClassGoesHere();

protected override void OnStop()