Skip to content

Instantly share code, notes, and snippets.

@an01f01
Created January 17, 2025 22:17
Show Gist options
  • Save an01f01/0b49d98a584737f09c6a0af68bbb3a15 to your computer and use it in GitHub Desktop.
Save an01f01/0b49d98a584737f09c6a0af68bbb3a15 to your computer and use it in GitHub Desktop.
unit AsyncThread;
interface
uses
{Delphi}
System.SysUtils
{Project}
;
type
IAsync = interface
['{65813BBC-12B6-4EF7-ABD2-E3B17576C66E}']
procedure Await(const AAwaitProc: TProc);
end;
{*
Usage:
Async(procedure begin MultipleParamProc('Edijs', 36) end).Await(FinalProc);
Async(Procedure1).Await(FinalProc);
*}
function Async(const AAsyncProc: TProc): IAsync;
implementation
uses
{Delphi}
System.Threading
, System.Classes
{Project}
;
type
TAsync = class(TInterfacedObject, IAsync)
strict private
FSelf: IAsync;
FAsyncProc: TProc;
FAwaitProc: TProc;
procedure Run;
public
constructor Create(const AAsyncProc: TProc);
procedure Await(const AAwaitProc: TProc);
end;
function Async(const AAsyncProc: TProc): IAsync;
begin
Result := TAsync.Create(AAsyncProc);
end;
procedure TAsync.Await(const AAwaitProc: TProc);
begin
FSelf := Self;
FAwaitProc := AAwaitProc;
// TThread.CreateAnonymousThread(Run).Start; // Older Delphi versions
TTask.Run(Run); // Newer Delphi versions
end;
constructor TAsync.Create(const AAsyncProc: TProc);
begin
inherited Create;
FAsyncProc := AAsyncProc;
end;
procedure TAsync.Run;
begin
FAsyncProc();
TThread.Queue(nil,
procedure
begin
if Assigned(FAwaitProc) then
FAwaitProc();
FSelf := nil;
end)
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment