I'd like to have a worker TThread which I utilize by sending messages from the main (UI) thread so it should be in a blocked state waiting for messages then if received, start some kind of processing according to the received message type. When done, it should send a message back to the main thread (UI) which will then display results. I was experimenting with PostMessage but the only part I could achieve is sending a message to the UI thread to display results.
unit threadtest;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
LMessages, LCLIntf;
const
UM_RESULT = WM_USER + 1;
type
TWorker = class(TThread)
private
textbuffer: String;
protected
procedure Execute; override;
end;
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
worker: TWorker;
protected
procedure UMResult(var Message: TLMessage); message UM_RESULT;
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
begin
worker := TWorker.Create(False);
end;
procedure TForm1.UMResult(var Message: TLMessage);
begin
Memo1.Lines.Add('Message: ' + String(Message.WParam));
end;
procedure TWorker.Execute;
begin
// Imitate to do something
Sleep(1000);
// Send message to UI thread
textbuffer := DateTimeToStr(Now);
LCLIntf.PostMessage(Form1.Handle, UM_RESULT, PtrInt(PString(textbuffer)), 0);
end;
end.
What is the best basic cross-platform workflow to do this?
How should I write a while not Terminated ... loop into TWorker.Execute that would catch messages and call functions within TWorker? Delphi tutorials talk about GetMessage but I didn't find them anywhere in LCLIntf.