gpt4 book ai didi

delphi - Delphi 中的线程消息循环挂起

转载 作者:行者123 更新时间:2023-12-03 15:13:23 26 4
gpt4 key购买 nike

我正在开发一个简单的 Delphi 程序,在该程序中,我尝试使用线程将程序的功能与其 GUI 分开,并在较长的任务期间保持 GUI 的响应能力等。基本上,我有一个“ Controller ”TThread 和一个“ View ”TForm。 View 知道 Controller 的句柄,它使用该句柄通过 PostThreadMessage 发送 Controller 消息。过去,我在非主窗体的窗体上使用这种模型没有任何问题,但由于某种原因,当我尝试将此模型用于主窗体时,线程的消息循环就会退出。

这是我的线程消息循环代码:

procedure TController.Execute;
var
Msg : TMsg;
begin
while not Terminated do begin
if (Integer(GetMessage(Msg, hwnd(0), 0, 0)) = -1) then begin
Synchronize(Terminate);
end;

TranslateMessage(Msg);
DispatchMessage(Msg);

case Msg.message of
// ...call different methods based on message
end;
end;
end;

要设置 Controller ,我这样做:

Controller := TController.Create(true); // Create suspended
Controller.FreeOnTerminate := True;
Controller.Resume;

为了处理主表单的消息,我尝试使用 Application.Run 和以下循环(紧接在 Controller.Resume 之后)

while not Application.Terminated do begin
Application.ProcessMessages;
end;

我被困在这里 - 任何帮助将不胜感激。

最佳答案

我基本上按原样测试了您的代码,并且运行良好。尝试在 GetMessage 返回 -1 后添加对 GetLastError 的调用以查看问题所在。

从代码中并不完全清楚您是否在 Controller 线程中创建窗口,但如果不是,我建议将 -1 而不是 0 作为 HWND 传递给 GetMessage,并删除 TranslateMessage/DispatchMessage 调用,因为它们后面的 case 语句应该处理您收到的任何消息。

此外,您不需要对错误执行“同步(终止)”。 Terminate 只是将“Termerated” bool 值设置为 true,因此您不需要同步它,并且您可以轻松地使用“Break”来打破循环,并具有相同的效果。

关于delphi - Delphi 中的线程消息循环挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2495681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com