Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateAnonymousThread with parameters

Tags:

delphi

In C# we have ParameterizedThreadStart that allows us to create a thread passing parameters to it, like so:

Thread thread = new Thread (new ParameterizedThreadStart(fetchURL));
thread.Start(url);

// ...
static void fetchURL(object url)
{
    // ...
}

I tried to reproduce on Delphi using CreateAnonymousThread but it seems that it does not accept arguments.

How can I create an anonymous thread and pass argument to the called procedure?

like image 848
sharklasers Avatar asked Mar 14 '23 13:03

sharklasers


1 Answers

TThread.CreateAnonymousThread takes an anonymous method as a parameter so you can put together a method that passes in any values that you would like. These values are captured so you will need to be careful when passing in the parameters. Read the "Variable Binding Mechanism" section in the anonymous method link above for more information about variable capture.

For example:

procedure DoSomething(const aWebAddress: String);
begin
end;

procedure BuildThread;
var
  myThread: TThread;
  fetchURL: string;
begin
  fetchURL := 'http://stackoverflow.com';
  // Create an anonymous thread that calls a method and passes in
  // the fetchURL to that method.
  myThread := TThread.CreateAnonymousThread(
    procedure
    begin
      DoSomething(fetchURL);
    end);
  ...
end;
like image 51
Graymatter Avatar answered Mar 24 '23 15:03

Graymatter