I
I
Igor2019-08-08 01:10:13
Delphi
Igor, 2019-08-08 01:10:13

Delphi Async Callable?

Colleagues, welcome.
The question, a call of asynchronous functions in Delphi interests.
At the first stage, I created the following unit

unit TD.AsyncFunc;

interface
 uses
  System.classes;

type
   TAsyncCallProc = reference to procedure;

type
 TAsyncFuncThread = class(TThread)
 private
    Fproc: TAsyncCallProc;
   { private declarations }
 protected
    procedure Execute; override;
 public
   constructor Create(const proc: TAsyncCallProc);


 published
   { published declarations }
 end;


procedure AsyncCallProc(const proc: TAsyncCallProc);

implementation

procedure AsyncCallProc(const proc: TAsyncCallProc);
var
 th: TAsyncFuncThread;
begin
 th:= TAsyncFuncThread.Create(proc)
end;

{ TAsyncFuncThread }

constructor TAsyncFuncThread.Create(const proc: TAsyncCallProc);
begin
  Fproc := proc;
  FreeOnTerminate := true;
  inherited Create(false);
end;

procedure TAsyncFuncThread.Execute;
begin
  Fproc;
end;

end.

But here it’s clear to the horse that this method is not thread-safe.
Use it like this:
procedure TMainForm.Button3Click(Sender: TObject);
begin

  AsyncCallProc(
    procedure
    begin
      (Sender as TButton).Text := 'Начал выполнение';
      Sleep(5000);
      (Sender as TButton).Text := 'Закончил выполнение';
    end);

end;

5d4b4c3f41b19575224286.gif

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zed, 2019-08-08
@IgorPI

And what, exactly, is the question? To make the code thread-safe, the call to the GUI must be wrapped in the Synchronize method (the call to Sleep, of course, does not need to be wrapped).
Here is a tutorial on using TTask and synchronization: Using Tasks from the Parallel Programming Library

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question