gpt4 book ai didi

multithreading - 从线程Delphi返回字符串

转载 作者:行者123 更新时间:2023-12-03 18:30:05 25 4
gpt4 key购买 nike

我正在使用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;

谢谢你的帮助。

最佳答案

您需要拦截线程终止。一种方法是使用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

关于multithreading - 从线程Delphi返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46257649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com