Skip to content

Instantly share code, notes, and snippets.

@sysrpl
Created July 28, 2017 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sysrpl/40505d25fbd38c4404f95225f21fe0a6 to your computer and use it in GitHub Desktop.
Save sysrpl/40505d25fbd38c4404f95225f21fe0a6 to your computer and use it in GitHub Desktop.
unit ThreadTest;
{$mode delphi}
interface
uses
Classes, SysUtils, LCLType, LCLIntf;
procedure SafePostMessage(Wnd: HWND; Msg: Cardinal);
implementation
{ TMessageThread }
type
TMessageThread = class(TThread)
private type
TMessage = class
Wnd: HWND;
Msg: Cardinal;
end;
private var
FList: TThreadList;
protected
procedure Post(Wnd: HWND; Msg: Cardinal);
procedure Execute; override;
public
constructor Create;
end;
constructor TMessageThread.Create;
begin
FList := TThreadList.Create;
inherited Create(False);
end;
procedure TMessageThread.Post(Wnd: HWND; Msg: Cardinal);
var
M: TMessage;
begin
WriteLn('Post message');
M := TMessage.Create;
M.Wnd := Wnd;
M.Msg := Msg;
FList.Add(M);
end;
procedure TMessageThread.Execute;
var
M: TMessage;
begin
FreeOnTerminate := True;
while not Terminated do
begin
Sleep(10);
repeat
M := nil;
FList.LockList;
M := FList.LockList.First;
FList.UnlockList;
if M <> nil then
begin
// PostMessage(M.Wnd, M.Msg, 0, 0);
WriteLn('New message');
FList.Remove(M);
M.Free;
end;
until M = nil;
end;
FList.Free;
end;
var
MessageThread: TMessageThread;
procedure SafePostMessage(Wnd: HWND; Msg: Cardinal);
begin
if MessageThread = nil then
MessageThread := TMessageThread.Create;
MessageThread.Post(Wnd, Msg);
end;
finalization
if MessageThread <> nil then
MessageThread.Terminate;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment