需求如下:我希望用c#写一个windows service程序,这个service程序里需要处理几种不同请求。 我的实现:添加一个windows service类型的类maincontroller,修改代码如下
static void main()
{
system.serviceprocess.servicebase[] servicestorun;
// run all user service in this process.
servicestorun = new system.serviceprocess.servicebase[] { new maincontroller(),
// main service
new service1 (),
new service2 (),
new service3 (),
};
system.serviceprocess.servicebase.run(servicestorun);
}
再向项目中添加windows service类型的类service1, service2, service3。查看代码可以发现service1,service2,service3大部分和maincontroller相同,但少了main()方法。添加相应代码到service1的onstart()、onstop()方法中,编译成功,然后安装运行该服务。但在查看服务输出时,发现maincontroller运行正常,但service1,service2,service3都没有被自动启动,除非在他们的构造函数里,主动调用onstart()。
你可以通过操作ServiceController实例来实现启动、暂停、停止、重启等。
http://www.cnblogs.com/downmoon/archive/2007/12/29/1019924.html
应该是在服务管理里面设置为自动启动吧!你也可以调用让他启动。
.net 里有个服务管理类;你可以根据服务名停止;启动等操作;
public static void StartService(string serviceName) { if (IsServiceExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { service.Start(); for (int i = 0; i < 60; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { break; } if (i == 59) { throw new Exception("Start Service Error\n" + serviceName); } } } } }
public static void StopService(string serviceName) { if (IsServiceExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { service.Stop(); for (int i = 0; i < 60; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { break; } if (i == 59) { throw new Exception("Stop Service Error\n" + serviceName); } } } } }