Windows服务中不会调用OnStop()方法

Windows服务中不会调用OnStop()方法

问题描述:

我已经编写了一个c#代码作为Windows服务,可以登录和注销网络中所有用户的所有登录和注销信息,并将其保存在服务器的表中.

我在

I have written a c# code as a windows service to logs all log on and log off of all users in a network and save them on a table in server.

I have used a

While 

循环中使用了

true 

条件,并检查了系统当前用户每1分钟在此循环中一次,因此当我打开系统电源时,我的服务将进入"正在启动"状态.

一切正常,但是问题是当我关闭系统时,

condition and check the system current user every 1 minutes 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 call when i shut down my system.I know the problem is about the status of the service when it starts because when i comment the While loop in

OnStart()

方法中注释While循环时,将完成

method the codes in

OnStop()

方法中的代码.

也许问题在于OnStart方法不是为了循环而设计的.它仅用于初始化服务.

http://msdn.microsoft.com/en-us/library/aa984464% 28VS.71%29.aspx [ ^ ]

Maybe the problem is that the OnStart method is not meant for a loop; it''s only meant for initializing the service.

http://msdn.microsoft.com/en-us/library/aa984464%28VS.71%29.aspx[^]

报价:

一旦服务开始运行,OnStart方法必须返回到操作系统.它不能永远循环或阻塞.

The OnStart method must return to the operating system once the service''s operation has begun. It must not loop forever or block.


不要在服务代码中添加循环.而是创建另一个包含循环代码的应用程序,并使用您服务的OnStart方法,启动该应用程序.然后通过OnStop方法杀死该应用程序.
Dont add loop in service code. Instead create one another application which has the loop code in it and fron your service''s OnStart method, start that application. And from your OnStop method, you kill that application.