Windows服务的OnStop()方法不会被调用 [英] Windows services's OnStop() method does not get called

查看:349
本文介绍了Windows服务的OnStop()方法不会被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用C#编写了Windows服务,用于记录所有用户登录和注销,并将它们保存在服务器上的表中.

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

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

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.

到目前为止一切都很好,但是问题是当我关闭系统时,不会调用OnStop()方法.我知道问题出在服务启动时的状态,因为当我在服务的OnStart()方法中注释while循环时,OnStop()方法将正确执行.

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.

推荐答案

OnStart(和OnStop)未完成未完成-它们旨在初始化服务,然后完成.我通常要做的是创建一个单独的线程(此在创建 TPL 之前,启动线程并完成.

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.

在您的情况下,线程然后将启动计时器,并等待停止信号,当服务停止时,可以从OnStop方法发送该信号.当停止信号到达时,应停止计时器.

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.

这篇关于Windows服务的OnStop()方法不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆