简体   繁体   English

Delphi线程返回值

[英]Delphi thread return value

Can someone explain to me how I get a return value from myThread calling function test? 有人可以向我解释我是如何从myThread调用函数测试中获得返回值的吗?

function test(value: Integer): Integer;
begin
  Result := value+2;    
end;

procedure myThread.Execute;
begin
  inherited;
  test(Self.fParameters);
end;

procedure getvaluefromthread();
var
  Capture : myThread;
begin
  list := TStringList.Create;
  Capture := myThread.Create(False);
  Capture.fParameters := 2;
  Capture.Resume;
end;
  1. Declare a class derived from TThread . 声明一个派生自TThread
  2. Add a field, or multiple fields, to contain the result value or values. 添加一个或多个字段以包含结果值。
  3. Set the result value field(s) in the overridden Execute method. 在重写的Execute方法中设置结果值字段。
  4. When the thread has finished, read the result from the thread instance. 线程完成后,从线程实例中读取结果。

As Remy points out, if you wish to return just a single Integer value, then you can use the ReturnValue property of TThread . 正如Remy所指出的,如果你只想返回一个Integer值,那么你可以使用TThreadReturnValue属性。 Use this in just the same way as described above. 以与上述相同的方式使用它。 Note that the value placed in ReturnValue is the value returned by the underlying OS thread. 请注意, ReturnValue中的值是底层OS线程返回的值。

You can listen for OnTerminate to find out when thread is done. 您可以侦听OnTerminate以找出线程何时完成。 Or call WaitFor . 或者致电WaitFor

Note that you set the thread's parameters after it starts running. 请注意,在开始运行后设置线程的参数。 Either create the thread suspended, or pass the parameters to the constructor. 创建挂起的线程,或将参数传递给构造函数。 Also, you should use Start rather than Resume . 此外,您应该使用Start而不是Resume The latter is deprecated. 后者已被弃用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM