不要使用Application.ProcessMessages
. 这是糟糕的代码设计的例子,你应该避免使用它。
相反,使用线程回调或消息。例子:
uAPISecureRequestThread.pas
unit uAPISecureRequestThread;
interface
uses
System.Classes;
type
TApiSecureRequestThread = class(TThread)
private
FResponse: String;
protected
procedure Execute; override;
public
constructor Create;
property Response: String read FResponse;
end;
implementation
constructor TApiSecureRequestThread.Create;
begin
inherited Create(TRUE);
FreeOnTerminate := TRUE; // automatically free thread on terminate
end;
procedure TApiSecureRequestThread.Execute;
begin
// do the work here and assign result to FResponse
end;
end.
uMainForm.pas
unit uMainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TfrmMain = class(TForm)
btCreateThread: TButton;
procedure btCreateThreadClick(Sender: TObject);
private
procedure ASRThreadTerminate(Sender: TObject);
public
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
uApiSecureRequestThread;
procedure TfrmMain.btCreateThreadClick(Sender: TObject);
var
asr_thread: TApiSecureRequestThread;
begin
asr_thread := TApiSecureRequestThread.Create;
try
asr_thread.OnTerminate := ASRThreadTerminate;
asr_thread.Start;
except
asr_thread.Free;
end;
end;
procedure TfrmMain.ASRThreadTerminate(Sender: TObject);
var
asr_thread: TApiSecureRequestThread;
begin
asr_thread := Sender as TApiSecureRequestThread;
// process asr_thread.Response here
end;
end.