如何重启Windows服务?

时间:2011-04-22 05:36:37

标签: c# asp.net visual-studio windows-services

我从http://www.csharp-examples.net/restart-windows-service/获得了一个片段来重新启动Windows服务,但我不确定将代码放在何处?

我需要在我的应用程序中安装Windows服务后重新启动它。

谢谢!

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);
    }

2 个答案:

答案 0 :(得分:2)

我认为你不应该在安装后加入。安装程序可能会在安装后启动安装程序,这似乎是一种混乱的方式。您可以创建一个小应用程序或.dll,如果您确实需要它可以执行此操作,并且可以在完成所有操作后从安装程序本身调用。但是,我会调查为什么您需要在安装后重新启动服务,因为这通常指向程序中的错误。应该更容易解决这个问题。

这个剪辑应该做重启的技巧。不要使用睡眠,因为服务可能花费的时间超过启动/停止时间,您将获得异常。

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

答案 1 :(得分:0)

假设您有一些安装该服务的应用程序,重启(或以其他方式控制服务)的代码应该在您的应用程序中运行

相关问题