简体   繁体   English

是否为C#Windows服务提供OnRestart()事件侦听器? 如何查看Windows服务是否已重新启动?

[英]Is there a OnRestart() event listener for a C# Windows service? How can I see if the Windows Service was Restarted?

I have a C# Windows Service. 我有一个C#Windows服务。 I have the following events 我有以下活动

protected override void OnStart(string[] args)
{    
    string url = "http://localhost:8080";
    SignalR = WebApp.Start(url);
    eventLog1.WriteEntry("Server running on " + url);
}

protected override void OnStop()
{
    eventLog1.WriteEntry(LogMessage.Message);   
    SignalR.Dispose();
}

The problem is that I am doing a 问题是我正在做一个

Environment.Exit(1);

when my service code has completed running its operations, I have properties set on my service such that it restarts after 1 minute (when it receives a failure). 当我的服务代码完成运行操作时,我在我的服务上设置了属性,以使其在1分钟后(接收到失败)后重新启动。 It seems that when it fails it doesn't actually hit the "stop" event so my log never gets written. 看来,当它失败时,它实际上并没有达到“停止”事件,因此我的日志从未被写入。 Is there a 有没有

OnRestart()

event or something like that? 事件还是类似的东西? I'm trying to figure out how to get my log written out before I exit the service. 我试图弄清楚如何在退出服务之前写出日志。 It would usually write the log when I manually clicked "Stop Service" from the services dialog in Windows. 当我在Windows的服务对话框中手动单击“停止服务”时,通常会写日志。 But I am no longer manually clicking stop to end the service, I am automatically restarting it and forcing a error in the service so I don't have to manually stop and re-start it. 但是,我不再手动单击“停止”以终止该服务,而是自动重新启动它并强制该服务出现错误,因此我不必手动停止并重新启动它。

You would think I would just be able to do 你会以为我会做

eventLog1.WriteEntry("blah blah");

before I exit the code, but I can't because It's out of scope and I'm exiting the code in a seperate class :( 在我退出代码之前,但是我不能,因为它超出了范围,我在一个单独的类中退出了代码:(

Can't you wrap a try/catch block around the section of code which is doing work? 您不能在正在执行的代码部分中包裹try / catch块吗? If it fails for whatever reason, it jumps in that catch block where you can raise the OnStop() event. 如果由于某种原因失败,它将跳转到该catch块中,在其中可以引发OnStop()事件。

try
    {            
        //Your service code
    }

    catch (Exception e)
    {
        OnStop();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM