Windows服务OnStop问题

use*_*384 0 .net c# service windows-services

我有一个Windows服务,我从一些博客和论坛,我主要提出的问题,在这里回答.服务很好.唯一的问题是我停止服务; 进一步粘贴是我在停止时在日志文件中看到的.

public partial class GBBInvService : ServiceBase
{
    private static readonly ILog log = LogManager.GetLogger(typeof(GBBInvService));
    System.Timers.Timer timer = new System.Timers.Timer();
    private volatile bool _requestStop=false;
    private ManualResetEventSlim resetEvent = new ManualResetEventSlim(false);


    public GBBInvService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        _requestStop = false;
        timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        timer.Interval = 18000;
        timer.Enabled = true;
        timer.Start();
        log.Info("GBBInvService Service Started");
    }

    protected override void OnStop()
    {
        log.Info("inside stop"); 
        if (!_requestStop)
        {
            log.Info("Stop not requested");
            timer.Start();
        }    
        else
        {
            log.Info("On Stop Called");
            WaitUntilProcessCompleted();
        }
    }

    private void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        log.Info("Timer elapsed at " + Convert.ToString(e.SignalTime)); 
        InvProcessing();
    }

    private void InvProcessing()
    {
        try
        {
            resetEvent.Reset();
           //*Processing here*
        }
        catch (Exception ex)
        {
            resetEvent.Set();
            log.Error(ex.Message); 
        }
    }


    private void WaitUntilProcessCompleted()
    {
        resetEvent.Wait();
    }
}
Run Code Online (Sandbox Code Playgroud)

服务正常停止并再次启动,但我不知道我的代码是否错误,因为日志文件显示:

2013-04-23 14:53:01,062 [6] INFO GBBInvService.GBBInventoryService [(null)] - 内部停止

2013-04-23 14:53:01,062 [6] INFO GBBInvService.GBBInventoryService [(null)] - 不要求停止

它是在内部(!_requestStop)而不是在内部else.我的代码错了吗?有人能够向我解释为什么它会进入(!_requestStop)而不是else语句.

任何建议都将非常感谢,因为我刚开始接受Windows服务和最近的日志记录.

nat*_*has 7

除非有什么改变_requestStop,否则它总是错误的.

ServiceBase没有将自动将_requestStop设置为true的代码,并且您的程序不会在任何地方更改它.

您的代码按预期运行.

当Windows服务管理器停止REQUEST时,将运行OnStop().有关详细信息,请访问http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.onstop.aspx

你会设置

_requestStop = true 
Run Code Online (Sandbox Code Playgroud)

在OnStop()的顶部,向程序的其余部分发出信号以完成任何任务.

也就是说,我不知道你希望这个程序做什么.我可以进一步提供有关它应该做什么的详细信息.