M_Mogharrabi
M_Mogharrabi

Reputation: 1389

Windows services's OnStop() method does not get called

I have written a Windows service in C# to log all user logons and logoffs, and save them in a table on a server.

I have used a while loop with true condition and check the system's current user every minute in this loop, so my service goes to 'Starting' status when i turn on my system.

Everything goes fine up to here, but the problem is that the OnStop() method does not get called when I shut down my system. I know that the problem is about the status of the service when it starts, because when I comment the while loop in my service's OnStart() method, the OnStop() method will get executed correctly.

Upvotes: 1

Views: 2233

Answers (2)

Despertar
Despertar

Reputation: 22382

OnStart() must return the operating system, below is the MSDN documentation,

A service application is designed to be long running. As such, it usually polls or monitors something in the system. The monitoring is set up in the OnStart method. However, OnStart does not actually do the monitoring. The OnStart method must return to the operating system once the service's operation has begun. It must not loop forever or block.


To set up a simple polling mechanism, you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Timer.Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring.

http://msdn.microsoft.com/en-us/library/aa984464%28v=vs.71%29.aspx

Upvotes: 3

Maarten
Maarten

Reputation: 22955

The OnStart (and OnStop) are not made to not finish - they are designed to initialize the service, and then finish. What I usually do is create a separate thread (this was before the TPL was created), start the Thread, and done.

In your case, the thread would then start a timer, and wait for a stop signal, which could be sent from the OnStop method when the service stops. When the stop signal arrives, it should stop the timer.

Upvotes: 4

Related Questions