【问题标题】:How to autostart windows services in C#如何在 C# 中自动启动 Windows 服务
【发布时间】:2014-10-13 03:10:05
【问题描述】:

我已经创建了一个 Windows 服务,它应该在 Windows 启动时自动启动,但由于某种原因它不起作用。我使用了下面的代码:

private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {
        using (ServiceController sc = new ServiceController(serviceInstaller1.ServiceName))
        {
            sc.Start();
        }
    }

使用 InstallUtil.exe 安装服务后,它会自动启动,但如果我重新启动,即使服务管理器中的配置为“自动”,它也不会启动。

我已经尝试更改为“自动(延迟启动)”,但没有任何改变。

我会很感激一些建议。

对不起,我的英语不好,我不是本地人。

谢谢

【问题讨论】:

标签: c# service windows-services


【解决方案1】:
namespace curUsers
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
    public ProjectInstaller()
    {
        var processInstaller = new ServiceProcessInstaller();
        var serviceInstaller = new ServiceInstaller();

        //set the privileges
        processInstaller.Account = ServiceAccount.LocalSystem;

        serviceInstaller.DisplayName = "curUsers";
        serviceInstaller.StartType = ServiceStartMode.Automatic;

        //must be the same as what was set in Program's constructor
        serviceInstaller.ServiceName = "curUsers";

        this.Installers.Add(processInstaller);
        this.Installers.Add(serviceInstaller);
    }

    private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {

    }

    private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {

    }
}
}

试试这个吧,我所有的windows服务都是用同样的方式开发的。这个也很好用。

【讨论】:

    【解决方案2】:

    不久前我构建了几个 Windows 服务。也许这将有助于解决您的问题

    // serviceInstaller1
     // 
     this.serviceInstaller1.ServiceName = "whoisthere";
     this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
     this.serviceInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceInstaller1_AfterInstall);
    

    【讨论】:

    • 我试过这个,但它不起作用。该服务在安装后工作正常,但在重新启动系统后无法正常工作。 Windows 似乎无法自行启动它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多