It is not recomended to write any business logic inside the service
OnStart() event. Let the service start smoothly with minimum required time. It gives better user experience. If you write any logic inside
OnStart() then the service will be in "
Starting" state untill the execution finished.
What you can do is move all of your logic into a separate method. Then create a
Thread by passing a
ThreadStart object created with the newly created method.
using System.Threading;
private void ExecuteMyBusiness()
{
this.WriteToFile("Service started {0}");
this.ScheduleService();
}
protected override void OnStart(string[] args)
{
Thread myBusinessThread = new Thread(new ThreadStart(ExecuteMyBusiness));
myBusinessThread.Start();
}
You can give this a try and if it works fine then well and good.
But, this is not all. You need to check in
OnStop() for if the thread has not finished the execution of the task assigned to it then it should wait for it to complete.
For that purpose, you need to incorporate following changes-
private bool isThreadRunning= false;
private void ExecuteMyBusiness()
{
isThreadRunning=true;
this.WriteToFile("Service started {0}");
this.ScheduleService();
isThreadRunning=false;
}
protected override void OnStop()
{
while(isThreadRunning)
{
Thread.Sleep(1000);
}
this.WriteToFile("Service stopped {0}");
this.Schedular.Dispose();
}
Ok. Is that all?
No, but it should resolve your current problem. You need to do various validation but this should be a good approach to start with.
Hopefully, it helps :)
Please let me know, if you have questions or problem in implementing this design.