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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 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——大语言模型本地部署的极速利器