How to restart windows service?

别等时光非礼了梦想. 提交于 2019-12-24 16:08:03

问题


I got a snippet from http://www.csharp-examples.net/restart-windows-service/ to restart windows service, but i am not sure as to where to place the code?

I need to restart windows service after my it is installed in my application.

Thanks!

EDITED

private void ProjectInstaller_OnAfterInstall(object sender, InstallEventArgs e)
    {
        //base.OnAfterInstall(e);
        ServiceController sc = new ServiceController("MyServiceName", Environment.MachineName);
        sc.Start();
        System.Threading.Thread.Sleep(3000);
        sc.Stop();
        System.Threading.Thread.Sleep(2000);
        sc.Start();
        System.Threading.Thread.Sleep(3000);
    }

回答1:


I don't think you should put in the after install. The installer will probably start the service anyway after installation, and this seems like a messy way to do it. You can create a small app or .dll that can do this if you really need it and can be called from the installer itself when everything is finished. However I would investigate why you need to restart the service after installation, as that mostly points to a bug in your program. Should be easier to resolve that.

This snipped should do the trick of restarting. Do not use sleep as service might take more than that time to start/stop and you will get an exception.

var sc = new ServiceController("MyService");
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));



回答2:


Assuming you have some application that installs the service, the code to restart (or otherwise control the service) should run in your application



来源:https://stackoverflow.com/questions/5752576/how-to-restart-windows-service

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