1.引用System.ServiceProcess命名空间
using System.ServiceProcess;
2.声明ServiceController变量
private ServiceController _controller;
3.假设服务名为ServicesName, 编写开始服务,停止服务,重启服务的代码如下
private void StopService() { this._controller = new ServiceController("ServicesName"); this._controller.Stop(); this._controller.WaitForStatus(ServiceControllerStatus.Stopped); this._controller.Close(); } private void StartService() { this._controller = new ServiceController("ServicesName"); this._controller.Start(); this._controller.WaitForStatus(ServiceControllerStatus.Running); this._controller.Close(); } private void ResetService() { this._controller = new ServiceController("ServicesName"); this._controller.Stop(); this._controller.WaitForStatus(ServiceControllerStatus.Stopped); this._controller.Start(); this._controller.WaitForStatus(ServiceControllerStatus.Running); this._controller.Close(); }
本文提供了使用C#来控制Windows服务的基本示例代码,包括启动、停止及重启服务的方法实现。通过ServiceController类,可以方便地对指定名称的服务进行状态查询及控制。
1万+

被折叠的 条评论
为什么被折叠?



