Start service automatically when windows start

不问归期 提交于 2019-12-25 03:06:54

问题


I install a service in windows server 2008 r2 , and want to start it when windows start

 class Program : ServiceBase
{
    ...    
    static void Main(string[] args)
    {
        ServiceBase.Run(new Program());
    }

    public Program()
    {
        this.ServiceName = "ABPS";
    }

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);

        this.start();//a method that start works
    }
    ...

回答1:


you should add installer to your application.

To determine how your service will be started, click the ServiceInstaller component and set the StartType property to the appropriate value.

  • Manual The service must be manually started after installation.
  • Automatic The service will start by itself whenever the computer reboots.
  • Disabled The service cannot be started.

you can start your service in AfterInstall event handler

void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
    using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
    {
         sc.Start();
    }
}



回答2:


You'll need to add an installer to your Service application, where you will need to set the StartType property.

http://msdn.microsoft.com/en-us/library/ddhy0byf%28v=VS.90%29.aspx

serviceInstaller.StartType = ServiceStartMode.Automatic;


来源:https://stackoverflow.com/questions/27456460/start-service-automatically-when-windows-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!