关于编程Windows服务:如何停止我的Windows服务?
// 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; }; };
所以:我刚刚创build了“我的testing服务”启动它并停止。 但是,当我正在查看我的Services.msc – “我的testing服务”继续运行,并停止只有当我点击“停止”链接。 为什么? – 为什么service.Stop()命令什么都不做?
ServiceController.Stop()也什么都不做!
如何测量C#中的系统空闲时间,不包括看电影等?
在窗体中绘制带有resize点的控件select矩形
编程添加路线
是否有附加到标准输出的缓冲区大小?
我怎样才能停止从Main()方法我的服务?
如果我有一个不受操作系统版本支持的API的DllImport(C#.NET),会发生什么情况
我如何以编程方式确定哪个应用程序正在locking文件?
连接到sql Server 2008 R2 Express时出错
.NET运行时(CLR),JIT编译器位于何处?
.NET(wpf)应用程序的内存pipe理
Stop功能发送停止信号。 它不会等待信号被接收和处理。
您将不得不等待Stop信号完成工作。 你可以通过调用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)阻塞操作时服务正在运行时它们不会被调用,并且仅在服务停止时返回。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。