简体   繁体   中英

Automatically start a windows service after install

Which of the two of these are preferable (and why) from the service installer, I've seen both mentioned on different websites (and here on stackoverflow Automatically start a Windows Service on install and How to automatically start your service after install? ).

// Auto Start the Service Once Installation is Finished.
this.AfterInstall += (s, e) => new ServiceController("service").Start();
this.Committed += (s, e) => new ServiceController("service").Start();

I consider the latter a little more proper (although a quick check of my codebase and I coded essentially the former). The difference I see is the chance of a Rollback happening. In the commit phase you are past the risk of a rollback. But if you start your service in the AfterInstall (which is just part of the overall Install phase (the four phases being Install, Rollback, Commit, Uninstall)) you have the possibility of a Rollback being issued by a subsequent InstallerClass. You would then need to stop your service and uninstall it (which Microsoft's default service installer classes do for you so it's not much of an issue.

In summary, there isn't too much of a difference.

Considering Committed is raised post-installation (that is, only when Install() calls have completed, and hence related events raised (if successful)) then I would say doing it at this point is "safest". in fact, I'm sure it is the last installation related event raised, and by doing so finalises the complete installation.

The Commit method is called only if the Install method of each installer in this instance's InstallerCollection succeeds.

Since Commit gathers information required for uninstallation, and it is possible to break and therefore for Rollback to be called throughout installation - you could possibly find yourself in a bind if services are already ambitiously running before completed, successful committing.

In C# in your service project you will have an installer class called ProjectInstaller.cs, modify it to override the AfterInstall event handler to autostart the service like the code below

[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
    public ProjectInstaller()
    {
        InitializeComponent();
    }

    protected override void OnAfterInstall(IDictionary savedState)
    {
        base.OnAfterInstall(savedState);
        using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
        {
            serviceController.Start();
        }
    }
}

This will automatically start your windows Service after installation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM