将Windows服务注册为已停止

本文关键字:注册 Windows 服务 | 更新日期: 2023-09-27 18:14:59

我用以下代码安装Windows Service:

ServiceBase.Run(new ServiceProcess(serviceName, serviceArgs));

从文档中我看到,这个方法在服务上也调用OnStart方法。

将Windows服务注册为已停止

private static InitialStartDone = false; // declared in service class
protected Overrride void OnStart(string[] args);
{
    if(!InitialStartDone)
    {
        InitialStartDone = true;
    }
    else
    {
        base.OnStart(args);
    }
}

尝试重写on start的默认行为,并使用静态变量来检测它是否第一次被调用

我研究了我们的项目,找到了自定义安装程序。我重写了方法OnCommitted,检查参数Delayed,选择现在启动服务还是以后手动启动。

[RunInstaller(true)]
public class CustomInstaller : System.Configuration.Install.Installer
{
    public CustomInstaller()
    {
        _installProcess = new ServiceProcessInstaller { Account = ServiceAccount.NetworkService };
        _installService = new CustomServiceInstaller(typeof(ServiceImplementation));
        //  Remove built-in EventLogInstaller:
        _installService.Installers.Clear();
        Installers.Add(_installProcess);
        Installers.Add(_installService);
    }
    public override void Install(IDictionary stateSaver)
    {
        //install
        base.Install(stateSaver);
    }
    protected override void OnCommitted(IDictionary savedState)
    {
        var delyed = bool.Parse(GetContextParameter(@"Delayed"));
        if (!delyed)
        {
            new ServiceController(GetContextParameter(ServiceNameKey)).Start();
        }
    }
    private string GetContextParameter(string parameterKey)
    {
        var parameterValue = Context.Parameters[parameterKey];
        if (string.IsNullOrWhiteSpace(parameterValue))
            throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, MissingRequiredParameterErrorMessage, parameterKey));
        return parameterValue;
    }
}