[英]How to stop Windows service programmatically
關於編程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()方法停止我的服務?
Stop
-function發送停止信號。 它不會等到信號被接收和處理。
你必須等到停止信號完成它的工作。 你可以通過調用WaitForStatus
來做到這一點:
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped);
有關詳細信息,請參閱: http : //msdn.microsoft.com/nl-nl/library/system.serviceprocess.servicecontroller.waitforstatus(v = vs.71).aspx
Environment.Exit
是一個令人討厭的。 不要使用它! 它以艱難的方式中止您的應用程序,而不在finally塊中執行任何清理,而不通過GC調用終結器方法,它終止所有其他的forground線程等。我可以想象您的應用程序在停止信號之前中止甚至離開了您的應用程序。
我在我的項目中使用以下功能
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);
}
在您的代碼示例中, service.Stop()
和ServiceController.Stop()
命令不執行任何操作,因為ServiceBase.Run(service)
阻塞操作時它們在服務運行時不會被調用,並且僅在服務停止時返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.