Thread Message Loop Hangs in Delphi
- by erikjw
Hello all. I have a simple Delphi program that I'm working on, in which I am attempting to use threading to separate the functionality of the program from its GUI, and to keep the GUI responsive during more lengthy tasks, etc. Basically, I have a 'controller' TThread, and a 'view' TForm. The view knows the controller's handle, which it uses to send the controller messages via PostThreadMessage. I have had no problem in the past using this sort of model for forms which are not the main form, but for some reason, when I attempt to use this model for the main form, the message loop of the thread just quits.
Here is my code for the threads message loop:
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;
To set up the controller, I do this:
Controller := TController.Create(true); // Create suspended
Controller.FreeOnTerminate := True;
Controller.Resume;
For processing the main form's messages, I have tried using both Application.Run and the following loop (immediately after Controller.Resume)
while not Application.Terminated do begin
Application.ProcessMessages;
end;
I've run stuck here - any help would be greatly appreciated.