关于编程Windows服务:如何停止我的Windows服务?
这是一个非常简化的示例代码(C#):
// Here is my service class (MyTestService.cs).
public class MyTestService:ServiceBase{
// Constructor.
public MyTestService(){
this.ServiceName = "My Test Service";
return;
}
};
// My application class (ApplicationClass.cs).
public static class ApplicationClass{
// Here is main Main() method.
public static void Main(){
// 1. Creating a service instance
// and running it using ServiceBase.
MyTestService service = new MyTestService();
ServiceBase.Run(service);
// 2. Performing a test shutdown of a service.
service.Stop();
Environment.Exit(0);
return;
};
};
所以:我刚刚创建了“我的测试服务”启动它并停止了。但是,当我查看我的Services.msc时 - “我的测试服务”继续运行并且仅在我单击“停止”链接时停止。为什么? - 为什么 service.Stop()命令什么都不做?
ServiceController.Stop()也什么都没做!
如何从Main()方法停止我的服务?
答案 0 :(得分:16)
Stop
- 函数发送停止信号。它不会等到信号被接收和处理。
你必须等到停止信号完成它的工作。你可以致电WaitForStatus
:
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped);
Environment.Exit
是一个讨厌的人。不要使用它!它以艰难的方式中止您的应用程序,而不在finally块中执行任何清理,而不通过GC调用终结器方法,它终止所有其他的forground线程等。我可以想象您的应用程序在停止信号之前中止甚至离开您的应用程序
答案 1 :(得分:7)
我在项目中使用以下功能
public static ServiceController GetService(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
return services.FirstOrDefault(_ => Contracts.Extensions.CompareStrings(_.ServiceName, serviceName));
}
public static bool IsServiceRunning(string serviceName)
{
ServiceControllerStatus status;
uint counter = 0;
do
{
ServiceController service = GetService(serviceName);
if (service == null)
{
return false;
}
Thread.Sleep(100);
status = service.Status;
} while (!(status == ServiceControllerStatus.Stopped ||
status == ServiceControllerStatus.Running) &&
(++counter < 30));
return status == ServiceControllerStatus.Running;
}
public static bool IsServiceInstalled(string serviceName)
{
return GetService(serviceName) != null;
}
public static void StartService(string serviceName)
{
ServiceController controller = GetService(serviceName);
if (controller == null)
{
return;
}
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running);
}
public static void StopService(string serviceName)
{
ServiceController controller = GetService(serviceName);
if (controller == null)
{
return;
}
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped);
}
答案 2 :(得分:3)
在您的代码示例中,service.Stop()
和ServiceController.Stop()
命令不执行任何操作,因为它们在服务运行时未被调用,因为ServiceBase.Run(service)
阻塞操作并且仅在服务停止时返回。 / p>