启动窗口服务并检查是否停止

时间:2013-08-14 10:14:08

标签: c# asp.net windows-services

我的问题在这里:Stop program when thread finished

我有一个窗口服务和一个aspx页面。在aspx页面中,我必须启动该服务。这个服务将运行一个线程,在线程完成后,它将停止服务。之后,我的aspx页面必须显示结果到屏幕。

所以,我必须:检查服务是否正在运行 - 启动服务 - 检查服务是否停止 - 将结果打印到屏幕。

目前,我的代码如下:

while(true){
    if(isServiceStop){
         MyService.Start();
         while(true){
              if(isServiceStop){
                   Print result;
                   break;
              }
         }
         break;
    }
}

这样,它会使我的CPU_Usage飙升,所以,我想知道是否有其他方法可以实现我的请求

2 个答案:

答案 0 :(得分:1)

创建两个EventWaitHandle个对象以指示服务的状态:

private EventWaitHandle ServiceRunningEvent;
private EventWaitHandle ServiceStoppedEvent;

// in service startup
ServiceRunningEvent = new EventWaitHandle(False, EventResetMode.Manual, "RunningHandleName");
ServiceStoppedEvent = new EventWaitHandle(False, EventResetMode.Manual,

“ServiceStoppedEvent”);

// Show service running
ServiceStoppedEvent.Reset();
ServiceRunningEvent.Set();

当服务退出时,让它翻转值:

ServiceRunningEvent.Reset();
ServiceStoppedEvent.Set();

在ASP.NET应用程序中,您以相同的方式创建等待句柄,但不是设置它们的值,而是等待它们。所以:

// if service isn't running, start it and wait for it to signal that it's started.
if (!ServiceRunningEvent.WaitOne(0))
{
    // Start the service
    // and wait for it.
    ServiceRunningEvent.WaitOne();
}

// now wait for the service to signal that it's stopped

ServiceStoppedEvent.WaitOne();

然而,我确实想知道为什么你要经常启动和停止服务。为什么不让服务一直运行,并在需要时发送信号呢?

答案 1 :(得分:0)

我发现该服务有WaitForStatus方法,所以我只需要使用下面的代码就可以了:

Myservice.WaitForStatus(ServiceControllerStatus.Stopped);
相关问题