带参数的CreateAnonymousThread [英] CreateAnonymousThread with parameters

查看:349
本文介绍了带参数的CreateAnonymousThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)
{
    // ...
}

我尝试使用 CreateAnonymousThread 在Delphi上重现,但似乎并没有

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 匿名方法作为参数,这样您就可以将传入的方法放在一起您想要的任何值。这些值将被捕获,因此在传递参数时需要格外小心。阅读上面的匿名方法链接中的变量绑定机制部分,以获取有关变量捕获的更多信息。

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.

例如:

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;

这篇关于带参数的CreateAnonymousThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆