Windows Service重启

Windows Service重启要通过ServiceController类来实现,具体请看http://msdn.microsoft.com/zh-cn/library/7fs05y7h(v=VS.80).aspx

重启的代码很简单,C#的代码和这个很类似(ServiceController是.NET Framework中的类,理所当然C#也能用)

System.ServiceProcess.ServiceController类

复制代码
代码
1 Sub Restart()
2 Dim controller As New System.ServiceProcess.ServiceController("ServiceName")
3 LogText("服务正在停止...")
4 controller.Stop()
5 LogText("服务已经停止...")
6 controller.Start()
7 LogText("服务已经重启...")
8 End Sub
复制代码

 

C#的形式:http://www.csharp-examples.net/restart-windows-service/
Start service

复制代码
1 public static void StartService( string serviceName, int timeoutMilliseconds)
2 {
3 ServiceController service = new ServiceController (serviceName);
4 try
5 {
6 TimeSpan timeout = TimeSpan .FromMilliseconds(timeoutMilliseconds);
7
8 service. Start ();
9 service. WaitForStatus ( ServiceControllerStatus . Running , timeout);
10 }
11 catch
12 {
13 // ...
14   }
15 } 
复制代码

Stop service

复制代码
1 public static void StopService( string serviceName, int timeoutMilliseconds)
2 {
3 ServiceController service = new ServiceController (serviceName);
4 try
5 {
6 TimeSpan timeout = TimeSpan .FromMilliseconds(timeoutMilliseconds);
7
8 service. Stop ();
9 service. WaitForStatus ( ServiceControllerStatus . Stopped , timeout);
10 }
11 catch
12 {
13 // ...
14   }
15 }
复制代码

 

Restart service

 

复制代码
1 public static void RestartService( string serviceName, int timeoutMilliseconds)
2 {
3 ServiceController service = new ServiceController (serviceName);
4 try
5 {
6 int millisec1 = Environment .TickCount;
7 TimeSpan timeout = TimeSpan .FromMilliseconds(timeoutMilliseconds);
8
9 service. Stop ();
10 service.WaitForStatus( ServiceControllerStatus .Stopped, timeout);
11
12 // count the rest of the timeout
13   int millisec2 = Environment .TickCount;
14 timeout = TimeSpan .FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));
15
16 service. Start ();
17 service.WaitForStatus( ServiceControllerStatus .Running, timeout);
18 }
19 catch
20 {
21 // ...
22   }
23 }
复制代码

 

 

 

posted @   Sunny Peng  阅读(2484)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
点击右上角即可分享
微信分享提示