【问题标题】:Passing a value to onTerminate with AnonymousThread使用 AnonymousThread 将值传递给 onTerminate
【发布时间】:2014-09-23 07:46:02
【问题描述】:

我有一个正在运行的线程应用程序正在计算一些更长的计算。

procedure TForm.calculationInThread(value: Integer);
var aThread : TThread;
begin
  aThread :=
    TThread.CreateAnonymousThread(
      procedure
      begin
        myCalculation(value);           
      end
    );
  aThread.FreeOnTerminate := True;
  aThread.OnTerminate := self.calculationInThreadEnd;
  aThread.Start;
end; 

还有一个calculationInThreadEnd的实现;

procedure TForm.calculationInThreadEnd(Sender: TObject);
begin
   doSomething;
end;

我可能会错过一些愚蠢的东西,但是如何将值传递给calculationInThreadEnd?我找到了

TThread.SetReturnValue(value);

但我如何在 onTerminate 调用中访问它?

解决方案

type THackThread = class(TThread);

procedure TForm1.calculationInThreadEnd(Sender: TObject);
var Value: Integer;
begin
    Value := THackThread(Sender as TThread).ReturnValue;  
end;

【问题讨论】:

    标签: multithreading delphi delphi-xe2


    【解决方案1】:

    OnTerminate 事件的Sender 参数是线程对象。所以你可以这样做:

    aThread :=
      TThread.CreateAnonymousThread(
        procedure
        begin
          myCalculation(value);           
          TThread.SetReturnValue(...);
        end
      );
    

    然后在OnTerminate 事件处理程序中你可以这样做:

    procedure TForm.calculationInThreadEnd(Sender: TObject);
    var
      Value: Integer;
    begin
      Value := (Sender as TThread).ReturnValue;
    end;
    

    更新

    返回值属性受到保护,因此您需要使用受保护的 hack 来访问它。

    【讨论】:

    • 我无法像那样访问它,它失败并出现错误 [dcc32 Error] Unit1.pas(33): E2362 Cannot access protected symbol TThread.ReturnValue and TThread does not contain a member named 'ReturnValue'
    • 然后使用受保护的黑客。然而,所有这些挣扎表明,这整个方法并不是最好的方法。
    • CreateAnonymousThread 正在返回 TThread,因此即使我尝试使用受保护的 hack,它也会编译但会因无效的类类型转换而崩溃。我喜欢 AnonymousThread 的简单性,一旦它启动我就不需要访问正在运行的线程,我只想知道,调用calculationInThreadEnd 时哪个线程结束了。 Ofc 我可以制作一个列表(fifo 或类似的东西),在那里添加线程标识符并在calculationInThreadEnd 函数中处理它。但我认为会有一个更优雅、更干净的解决方案。
    • 与受保护的黑客一起工作正常。
    • 你是对的,我错过了另一个演员阵容。对于更复杂的事情,我想我会采用不同的方法,在这种情况下,为简单起见,我将采用 hack。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多