首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TThread执行结果

TThread执行结果
EN

Stack Overflow用户
提问于 2013-09-08 14:12:53
回答 1查看 260关注 0票数 2

这段代码似乎不是获得线程结果的适当方法,即使表单不是冻结的,而且我可以执行不同的其他任务,也许是另一个请求,所以线程的数量并不总是等于一个,它可能同时达到5个请求,但不依赖于彼此。

如何以“好”的方式做到这一点?

代码语言:javascript
复制
function TEApi.FApiRequest(Request: string) : string;
var
  RequestThread : TApiSecureRequest; {TThread}
begin
  RequestThread := TApiSecureRequest.Create(Self, Request);
  while(NOT RequestThread.Terminated) do
    Application.ProcessMessages;
  Result := RequestThread.FResponse;
  RequestThread.Free;
end;

procedure TApiSecureRequest.Execute;
begin
  {do some HTTP requests, which is freezing the Mainform without threading}
  FResponse = Result_of_execution;
  Terminate;
end;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-08 15:10:49

不要使用Application.ProcessMessages。这是错误的代码设计的例子,您应该避免使用它。

相反,使用线程回调或消息。示例:

uAPISecureRequestThread.pas

代码语言:javascript
复制
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

代码语言:javascript
复制
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.
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18684667

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档