0

我创建了一个设置为自动启动的 Windows 服务。我还在安装程序中添加了以下代码:

    public ProjectInstaller()
    {
        InitializeComponent();
        serviceProcessInstaller1.AfterInstall += new InstallEventHandler(serviceProcessInstaller1_AfterInstall); 
    }

    void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {
        try
        {
            var sc = new ServiceController(serviceInstaller1.ServiceName);
            sc.Start();
        }
        catch
        {
        }
    }

    protected override void OnCommitted(IDictionary savedState)
    {
        try
        {
            var sc = new ServiceController(serviceInstaller1.ServiceName);
            sc.Start();
        }
        catch
        {
        }
    }

该服务已正确安装,但它永远不会启动。

这可能是什么原因?

4

5 回答 5

1

也许您需要放入一些临时诊断日志记录,也许使用System.IO.File.WriteAllText();. 我知道这不是您要寻找的答案,但它可能会给您最快的解决方案!

try
{
    var sc = new ServiceController(serviceInstaller1.ServiceName);
    sc.Start();
    System.IO.File.WriteAllText(@"c:\temp\servicestart.txt", "Service started");
}
catch (Exception ex)
{
    System.IO.File.WriteAllText(@"c:\temp\servicestart.txt", ex.Message);
}
于 2012-06-05T03:28:37.107 回答
0

I've created a service a while ago and what mine differs from yours is that you declared this way

var sc = new ServiceController(serviceInstaller1.ServiceName);

mine instead of taking the serviceInstaller1.ServiceName I was giving the name via a simple string like this

var sc = new ServiceController("MyService");

I think this isn't the problem at all, but when talking about services everything is worth a try

EDIT: giving a look at it now I've seen that the name I used was actually the DisplayName not the service name, try passing it manually or by using serviceInstaller1.DisplayName

于 2012-06-04T18:22:28.513 回答
0

确保在您的Main()函数中有此行:

ServiceBase.Run(new ServiceClass());

我有几次离开时感到内疚 Application.Run(new Class()); (如果你是从 Windows 窗体应用程序开始的)

于 2012-06-04T18:15:51.410 回答
0

它是否可能依赖于另一个服务。或者您是否尝试过延迟启动?

于 2012-06-05T00:22:04.723 回答
-1

这对我有用

protected override void OnAfterInstall(IDictionary savedState)
{
      base.OnAfterInstall(savedState);
      System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName);
      sc.Start();
}
于 2016-09-15T13:41:38.313 回答