Calling a function from a function pointer in Delphi
I'm trying to build a generic worker thread in Delphi, one that I can pass a function/procedure (doesn't matter) as an argument and let it execute.
My guess is to add a field in the TThread
class and call it from TThread.Execute
.
So the code outside the thread is gonna be:
MyThread := TWorkerThread.Create(True); Mythread.CallBackF := @开发者_开发问答Foo; try MyThread.Resume; except MyThread.Free; end;
How do I keep a reference of @foo
in the TWorkerThread
and call it from inside Execute
?
Also, a good start into using generic threads would be AsyncCalls or Omni Thread Library.
I do not pretend to be an expert on threading, 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 got any procedure, like
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);
Take a look at QueueUserWorkItem function.
It executes arbitrary function in a thread, without requiring you to create one. Just don't forget to switch IsMultithreaded global variable to True.
精彩评论