How to make GUI wait for windows service?

萝らか妹 提交于 2019-12-01 15:34:45

问题


I wrote a windows service and a gui for it. Of course gui mainly depends on the service. Is there a way for gui to wait for the service? Sometimes I need to reload service config from the gui and restart the service.

I was thinking about 2 solutions: 1. using while and sleep to wait for service controller status to change (of course the simplest solution :P) 2. implementin INotifiPropertyChanged interface somewhere (this looks to complicated for this trivial problem).

I was wondering is there more elegant way of doing it? Is there an event that I am missing somewhere?


回答1:


ServiceController has a method WaitForStatus where you pass it an argument of type ServiceControllerStatus. You can use it like this:

controller.WaitForStatus(ServiceControllerStatus.Running);



回答2:


I'd probably spawn a seperate thead to simply poll and see when your service controller status has changed, when the change occurs kill this thread. Then simply re spawn the thread when you need to start re-poll

Darknight




回答3:


Use an EventWaitHandle. Your GUI can wait on the WaitHandle and the service will set it which will trigger the GUI to continue on with what it was doing before it started waiting. No polling, no looping, no mess.

This great article on C# threading is probably a better resource for info on WaitHandles




回答4:


Use a kernel Event object. When you start both apps, have them create or open a named Event object, then wait on it. The other can signal it, flipping the state thus allowing the other app to stop waiting and run.




回答5:


ServiceController mysqlServiceController = new ServiceController();
mysqlServiceController.ServiceName = "MySql";
var timeout = 3000;

myServiceController.Start();

try
{
    //Wait till the service runs mysql      
    ServiceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, new TimeSpan(0, timeout, 0));
}
catch (System.ServiceProcess.TimeoutException)
{
    MessageBox.Show(string.Format("Starting the service \"{0}\" has reached to a timeout of ({1}) minutes, please check the service.", mysqlServiceController.ServiceName, timeout));
}


来源:https://stackoverflow.com/questions/1254953/how-to-make-gui-wait-for-windows-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!