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

被刻印的时光 ゝ 提交于 2019-12-11 10:26:14

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/11389428/windows-servicess-onstop-method-does-not-get-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!