Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi thread return value

Can someone explain to me how I get a return value from myThread calling function test?

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;
like image 363
chaz Avatar asked May 29 '26 21:05

chaz


1 Answers

  1. Declare a class derived from 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.
  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. 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.

You can listen for OnTerminate to find out when thread is done. Or call 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. The latter is deprecated.

like image 188
David Heffernan Avatar answered Jun 02 '26 20:06

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!