防止 Delphi 服务不响应

Prevent Delphi Service from not responding

我的问题如下: 我在 Delphi 东京实现了 Windows 服务,但恕我直言,这不是版本问题,而是设计问题。 我使用以下代码暂停我的服务并在该状态下响应。

procedure TMyService.ServiceExecute(Sender: TService);
begin
    while not Terminated do
    begin
      MyProductiveFunction;
      Delay(10000);
    end;
end;

procedure TMyService.Delay(Milliseconds: integer);
var
  Tick: DWord;
  Event: THandle;
begin
  LogOnLevel(clogger, CAS_LOGGER.Debug, '', ['Delay', 'ENTER', 'Delayed for ' + Milliseconds.ToString]);
  Event := CreateEvent(nil, False, False, nil);
  try
    Tick := GetTickCount + DWord(Milliseconds);
    while (Milliseconds > 0) and (MsgWaitForMultipleObjects(1, Event, False, Milliseconds, QS_ALLINPUT) <>
      WAIT_TIMEOUT) do
    begin
      ServiceThread.ProcessRequests(False);
      if Terminated then
        exit;
      Milliseconds := Tick - GetTickCount;
    end;
  finally
    CloseHandle(Event);
  end;
end;

函数 I 运行 有时非常耗时。当我在延迟过程中尝试停止服务时,它停止了,一切都很好。但是,当我在 运行ning "MyProductiveFunction" 时尝试停止服务时,它会说服务没有响应,之后除了通过任务管理器将其终止外,没有其他方法可以终止服务。 是否有更好的方法来实现该服务将独立于其实际状态进行响应?

您必须像编写延迟函数一样编写MyProductiveFunction:定期处理请求并在服务被要求终止时终止该函数。

相反,您还可以创建另一个线程来执行 MyProductiveFunction 并从 ServiceExecute 调用 ProcessRequest 并检查终止。当请求终止时,您必须终止另一个线程。最好的办法是让另一个线程检查某些共享的东西,例如 TEvent 以终止,或者 ServiceExecute 可能 kill/abort 该线程。

感谢您的支持。

我在这里使用了 Remys post 的代码框架:

Delphi Windows Service Design

效果很好。感谢那个伟大的社区,感谢 Remy