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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With