我有一个在 Apache 上运行的基于 Delphi TWebModule ISAPI 的项目。我的一个事件处理程序包含可能需要几分钟才能处理的逻辑。我想生成一个单独的进程/线程来执行逻辑并立即将 html 返回到浏览器。 html 将具有 AJAX 客户端调用来获取流程进度的定期更新。
我尝试过使用TThread,但发现它要等待执行代码结束才返回。
示例:
procedure Tmainweb.DoLongProcess(Sender: TObject; Request: TWebRequest;
Response: TWebResponse; var Handled: Boolean);
var
ProcessThread: TProcessThread;
begin
ProcessThread := TProcessThread.Create(True);
ProcessThread.Execute;
Handled := True;
Response.Content := '<html><body>Processing - would also include ajax stuff to get periodic updates</body></html>
end;
TProcessThread 是我的处理线程,可能需要几分钟才能完成。当我运行这个应用程序时,我认为控制将在 ProcessThread.Execute 之后立即继续。但事实并非如此。相反,它会等待执行过程中的代码完成。
我怎样才能做到这一点?如何生成异步进程以使浏览器不处于等待状态?
最佳答案
只是旋转达里安的答案。 这是一个回答您问题的示例:
type
TProcessThread = class(TThread)
protected
procedure Execute; override;
public
constructor Create;
end;
constructor TProcessThread.Create;
begin
inherited Create( false);
Self.FreeOnTerminate := true;
end;
procedure TProcessThread.Execute;
begin
while not Self.Terminated do begin
{- Do some heavy work }
end;
{- free by myself at last ! }
end;
-
// In your TmainWeb.DoLongProcess
ProcessThread := TProcessThread.Create; // Thread will free itself when ready.
Handled := True;
关于delphi - 在 TWebModule Handler 中生成新的线程/进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8505640/