【问题标题】:Return String from Thread Delphi从线程 Delphi 返回字符串
【发布时间】:2018-02-25 17:06:58
【问题描述】:

我正在使用 Delphi XE6。

我有一个线程,我在其中传递了一个 ID,并希望取回由该线程创建的字符串。我查看了所有示例,但它们都在线程运行时返回值我只需要它 OnTerminate。

从表单调用线程:

StringReturnedFromThread := PrintThread.Create(MacId);

PrintThread = class(TThread)
  private        
    MyReturnStr, PrinterMacId : String;
  public
        constructor Create(MacId: String); reintroduce;
        procedure OnThreadTerminate(Sender: TObject);
  protected
    procedure Execute; override;
  end;

constructor PrintThread.Create(MacId: String);
begin
    inherited Create(False);
    OnTerminate := OnThreadTerminate;
    FreeOnTerminate := True;
    PrinterMacId := MacId;
end;

procedure PrintThread.Execute;
begin
    PrepareConnection;
    MyReturnStr:= RequestPrintJobs(PrinterMacId);
end;

procedure PrintThread.OnThreadTerminate(Sender: TObject);
begin


end;

感谢您的帮助。

【问题讨论】:

  • 好的,然后从 OnTerminate 事件处理程序中获取它。那个是在主线程的上下文中调用的,所以它是安全的。
  • 我要不要改成这样的函数; OnThreadTerminate:字符串;然后结果 := MyReturnStr;
  • 不,你已经正确了(它必须与事件原型保持匹配)。只需以某种方式在 OnThreadTerminate 处理程序中处理您的字符串(我不知道您想做什么)。在该方法中,访问主线程的东西是安全的。
  • 我希望它回到表单中。我应该创建一个读取吗?
  • 代码设计不好,但您甚至可以编写该事件处理程序作为该表单的一部分。或者另一个不好的做法是从当前处理程序访问预先声明的全局表单变量。或者将表单引用传递并存储到该线程并从线程字段访问它。

标签: multithreading delphi return-value delphi-xe6


【解决方案1】:

您需要拦截线程终止。一种方法是使用 TThread.OnTerminate 事件/回调。

下面是示例代码。

线程单元:

unit Processes;

interface

uses
  System.Classes;

type
  TProcess = class(TThread)
  private
    FReturnStr: string;
    FMacId: string;
  protected
    procedure Execute; override;
  public
    property MacId: string read FMacId write FMacId;
    property ReturnStr: string read FReturnStr write FReturnStr;
    constructor Create;
  end;

implementation

constructor TProcess.Create;
begin
  inherited Create(True);
  FreeOnTerminate := True;
end;

procedure TProcess.Execute;
begin
  // Some hard calculation here
  FReturnStr := FMacId + 'BLA';
end;

end.

线程使用:

uses Processes;

procedure TForm1.Button1Click(Sender: TObject);
var P: TProcess;
begin
  // Create the thread
  P := TProcess.Create;
  // Initialize it
  P.MacId := 'MID123';
  // Callback handler
  P.OnTerminate := OnProcessTerminate;
  // Let's go
  P.Start;
end;

procedure TForm1.OnProcessTerminate(Sender: TObject);
var P: TProcess;
begin
  // The thread has been terminated
  P := TProcess(Sender);
  ShowMessage(P.ReturnStr);
end;

线程将在终止时返回MID123BLA

【讨论】:

  • 谢谢,这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2014-12-04
  • 2021-12-01
  • 1970-01-01
  • 2016-10-20
  • 1970-01-01
  • 1970-01-01
  • 2016-05-20
  • 1970-01-01
相关资源
最近更新 更多