带参数的 CreateAnonymousThread

sha*_*ers 4 delphi

在 C# 中,我们ParameterizedThreadStart允许我们创建一个向它传递参数的线程,如下所示:

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

// ...
static void fetchURL(object url)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用 Delphi 在 Delphi 上重现,CreateAnonymousThread但它似乎不接受参数。

如何创建匿名线程并将参数传递给被调用的过程?

Gra*_*ter 6

TThread.CreateAnonymousThread匿名方法作为参数,因此您可以组合一个方法,该方法可以传入您想要的任何值。这些值会被捕获,因此您在传递参数时需要小心。阅读上面匿名方法链接中的“变量绑定机制”部分,了解有关变量捕获的更多信息。

例如:

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;
Run Code Online (Sandbox Code Playgroud)