Hi,
I'm trying to avoid the hard-sync (Synchronize, WaitFor, OnTerminate)
approach when I'm communicating with a background thread. I'm trying to
do it with posting messages to the background thread (thread has got a
message loop) and from the background thread (to a thread-monitoring
class having allocated a handle and a window procedure). I'm not sure -
am I doing it the right way? Please advice.
I have defined a structure for data of request/response notification and
methods for producing and consuming the data:
type
TJobMsgData = packed record
CmdId: Integer;
CmdProgress: Integer;
MsgStr: PChar;
end;
PJobMsgData = ^TJobMsgData;
function ProduceJobMsgData(const CmdId, CmdProgress: Integer;
const MsgStr: PChar): PJobMsgData;
begin
Result := AllocMem(SizeOf(TJobMsgData));
Result.CmdId := CmdId;
Result.CmdProgress := CmdProgress;
Result.MsgStr := StrNew(MsgStr);
end;
procedure ConsumeJobMsgData(var PMsgData: PJobMsgData);
begin
if (PMsgData <> nil) then
begin
StrDispose(PMsgData.MsgStr);
FreeMem(PMsgData);
PMsgData := nil;
end;
end;
Now when I want to post a request/response notification (to the thread
or to the window), I use:
// produce message data and post it to a thread or window
pMsgData := ProduceJobMsgData(123, 0, 'Blah...');
PostMessage(MsgWnd<or thread>, WM_XXX, 0, Integer(pMsgData));
The receiving thread/window "consumes" the data this way:
// react on received message data, do this then to that...
// finally somebody should deallocate the memory:
pMsgData := PJobMsgData(Message.LParam);
ConsumeJobMsgData(pMsgData);
Is this a valid approach?
Thanks in advance,
mikk