I’m sure it’s related to the GetMessage call as if I replace it with ‘while(not terminated) do;’, the app’d close peacefully. Is it because GetMessage freezes the thread? Could you give more info about the problem itself and eventually a solution. Thanks!
type TListener = class(TThread)
procedure Execute; override;
destructor Destroy; override;
end;
var l: TListener;
msg:TMsg;
procedure TListener.Execute;
begin
while(not Terminated) do
while(GetMessage(msg, Cardinal(-1), 0, 0)) do;
end;
destructor TListener.Destroy;
begin
inherited; // <-- freeze here!
end;
begin
l:= TListener.Create();
sleep(1000);
l.Free;
end.
Consider the termination condition of your inner loop.
GetMessageblocks until a message arrives, and it only returnsFalsewhen it processes awm_Quitmessage.The thread that calls
Freeon yourTThreadis waiting for the other thread to terminate —TThread.DestroycallsWaitFor. But your thread never terminates because it evidently never receives awm_Quitmessage.Since you’re already using messages, don’t bother checking
Terminated. That only checks whether someone has calledTerminateon your thread object, but since doing so clearly isn’t the way to notify the thread that it should stop running, it’s pointless to check it. (If theTerminatemethod were virtual, you could override it and have it post awm_Quitmessage to the thread, but it isn’t, so you can’t.)