检查 Windows 服务是否被手动停止或由于某些异常

Check if Windows service is stopped manually or due to some exception

我如何才能知道服务是由于某些异常而停止还是在以下事件中手动停止?

protected override void OnStop()
{
    if (Service is stopped manually)
    {
        //Log Something
    }
    else if (Service is stopped due to some exception)
    {
        GenerateNotification();
        //Log Something here
    }

    timer.Stop();
    timer = null;
}

我的OnStart事件如下:

protected override void OnStart(string[] args)
{

    timer = new Timer(ConfigurationReader.IntervalInSeconds * 1000D);
    timer.AutoReset = true;
    timer.Elapsed += new ElapsedEventHandler(ProcessNotifications);
    timer.Start();
}

Actually when I'm stopping the sevice manually, I dont want some of the logic to be executed..But when its stopped due to some exception, I need to do some logic

错误将出现在 windows 事件日志中,但异常不会调用 onStop。 您可以在 worker 方法中处理异常并记录所有异常数据,在 onStop 方法中您可以记录有关正常停止的信息。

当您以正常方式停止服务时,服务管理器会调用 onStop 方法,然后您无需执行任何操作。 但是,如果发生异常,您可以在 onStart 方法或 worker 方法中处理它,并且可以执行额外的逻辑。 在异常情况下停止不调用 onStop 方法。

你的情况:

private void ProcessNotificationsWithExceptionHandling()
{
    try
    {
        ProcessNotifications();
    }
    catch(Exception ex)
    {
        GenerateNotification();
        //Log Something here
    }
}

并更改:

timer.Elapsed += new ElapsedEventHandler(ProcessNotifications);

timer.Elapsed += new ElapsedEventHandler(ProcessNotificationsWithExceptionHandling);