How to handle the onStop event in the Windows Service created in C#.
Just have OnStop method overriden:
protected override void OnStop()
{
// Your code goes here.
}
What is it you want to do? If you are fine with your service just stopping, do nothing. You don't need to handle it to actually get the service to stop - it is there to allow you to do stuff when the service receives the stop notification from Windows.
In your class that derives from ServiceBase
, you need to override the OnStop
method:
protected override void OnStop()
{}
You can then put your logic that should be executed when the service is stopping in there.
Note that Windows allows a short time frame for a service to stop (around 30 seconds I think) - after this it will report that the service cannot stop. This means you cannot do anything too lengthy in the OnStop
method. It is usually useful to log that your service received the stop event.
Please find below is a code snippet....
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
Timer myTimer = new Timer(5000);
myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
myTimer.Interval = 20000;
myTimer.Enabled = true;
}
private static void myTimer_Elapsed(Object source, ElapsedEventArgs e)
{
DBConnection dbc = new DBConnection();
dbc.sendRequest();
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
try
{
logger.Debug("In try block");
}
catch (Exception ex)
{
logger.Debug("In catch block : " + ex.Message.ToString());
}
}
I suppose this was something to do with the operating system. I deployed my service on Win2k3 and it worked just fine. It started perfectly and stopped when i stopped it from Services.msc. I was trying to deploy the service on WinXP earlier. Please let me know if anyone else has faced such an issue.