Calling a function from a function pointer in Delphi

I am trying to create a shared workflow in Delphi, one of which I can pass a function / procedure (doesn't matter) as an argument and let it execute.

My guess is to add a field to the class TThreadand call it from TThread.Execute.

Thus, the code outside the stream will be as follows:

  MyThread: = TWorkerThread.Create (True);
  Mythread.CallBackF: = @Foo;
  try
    MyThread.Resume;
  except
    MyThread.Free;
  end;

How to save a link @footo TWorkerThreadand call it from the inside Execute?

+3
source share
3 answers

QueueUserWorkItem.

, . IsMultithreaded True.

+4

I do not pretend to be an expert in streaming, but I think this will do it:

interface

    type
      TProcRef = reference to procedure;
      TWorkerThread = class(TThread)
      public
        proc: TProcRef;
        procedure Execute; override;
        class procedure RunInThread(AProc: TProcRef);
      end;

implementation

procedure TWorkerThread.Execute;
begin
  inherited;
  proc;
end;

class procedure TWorkerThread.RunInThread(AProc: TProcRef);
begin
  with TWorkerThread.Create(true) do
  begin
    FreeOnTerminate := true;
    proc := AProc;
    Resume;
  end;
end;    

Then, if you have any procedure, for example

procedure P;
begin
  while true do
  begin
    sleep(1000);
    beep;
  end;
end;

you can just do

procedure TForm1.Button1Click(Sender: TObject);
begin
  TWorkerThread.RunInThread(P);
end;

You can even do

TWorkerThread.RunInThread(procedure begin while true do begin sleep(1000); beep; end; end);
+4
source

Source: https://habr.com/ru/post/1770822/


All Articles