如何重新启动windows服务? [英] How to restart windows service?

查看:160
本文介绍了如何重新启动windows服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 http://www.csharp-examples.net/一个片段重新启动窗口服务/ 重新启动Windows的服务,但我不知道在何处放置code?

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

谢谢!

EDITED

 私人无效ProjectInstaller_OnAfterInstall(对象发件人,InstallEventArgs E)
    {
        //base.OnAfterInstall(e);
        ServiceController的SC =新的ServiceController(服务名,Environment.MachineName);
        sc.Start();
        System.Threading.Thread.Sleep(3000);
        sc.Stop();
        System.Threading.Thread.Sleep(2000);
        sc.Start();
        System.Threading.Thread.Sleep(3000);
    }


解决方案

我不认为你应该把在安装之后。安装程序可能会在安装后反正启动该服务,这似乎是一个混乱的方式做到这一点。您可以创建一个小的应用程序或.dll可以做到这一点,如果你真的需要它,当一切都完了可以从安装程序本身被调用。不过,我会调查的为什么您需要在安装后重新启动该服务,因为这主要是指向你的程序中的错误。应该比较容易解决。

此文档片断应该做重新的把戏。不要使用睡眠作为服务可能会比那个时候更开始/停止,你会得到一个异常。

  VAR SC =新的ServiceController(则将MyService);
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped,TimeSpan.FromSeconds(30));
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running,TimeSpan.FromSeconds(30));

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

解决方案

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

这篇关于如何重新启动windows服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆