如果配置错误且无事可做,退出Windows Service OnStart的正确方法是什么?

cha*_*r m 29 c# service windows-services

这就是我得到的:

protected override void OnStart(string[] args)
{
    if (SomeApp.Initialize())
    {
        SomeApp.StartMonitorAndWork();
        base.OnStart(args);
    }
}

protected override void OnStop()
{
    SomeApp.TearDown();
    base.OnStop();
}
Run Code Online (Sandbox Code Playgroud)

这里Initialize读取一个配置文件,如果有错,那就没什么可做的,所以服务应该停止!如果配置正常StartMonitorAndWork启动:

Timer(new TimerCallback(DoWork), null, startTime, loopTime);
Run Code Online (Sandbox Code Playgroud)

和DoWork定期轮询数据库.

如果Initialize失败(我检查日志文件),我尝试从管理工具 - >服务停止服务,我得到:

Could not stop the SomeService on Local Computer. The service did not return an error. 
This could be internal Windows error or an internal service error. 
If the problem persists, contact system administrator.
The question is: 
"Is exiting OnStart without doing nothing enough if Initialize returns false?

或者应该有这样的事情:

private void ExitService()
{
    this.OnStop();
    System.Environment.Exit(1);
}

protected override void OnStart(string[] args)
{
    if (ObjectFolderApp.Initialize())
    {
        SomeApp.StartMonitorAndWork();
        base.OnStart(args);
    }
    else
    {
        ExitService();
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢和BR - 马蒂

编辑:我想出了这样的事情:

protected override void OnStart(string[] args)
{
    try
    {
        if (SomeApp.Initialize())
        {
            SomeApp.StartMonitorAndWork();
            base.OnStart(args);
        }
        else
        {
            Stop();
        }
    }
    catch
    {
        Stop();
    }
}

protected override void OnStop()
{
    try
    {
        SomeApp.TearDown();
        base.OnStop();
    }
    catch
    {
        base.OnStop();
    }
}
Run Code Online (Sandbox Code Playgroud)

Nis*_*sus 10

在测试了我个人喜欢打电话的所有方法之后

Environment.FailFast("Configuration is wrong.");
Run Code Online (Sandbox Code Playgroud)

主要目标是在事件日志中写入失败的解释,并且FailFast会影响服务的恢复设置.因此,如果您配置恢复和配置正确,您的服务将自动启动.


Mik*_*son 2

如果返回 false,我会在事件日志中记录一个错误Initialize(),并显示一些明智的消息,说明它失败了,并且您应该建议OnStop()在失败时致电。确保正确关闭服务是一个很好的做法。

另请参阅此相关 SO 问题开发新闻组线程