首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IdHTTP获得响应线程

IdHTTP获得响应线程
EN

Stack Overflow用户
提问于 2014-12-14 08:10:16
回答 1查看 3.3K关注 0票数 1

如何使用线程对这段代码,这个代码使程序采取快速锁定线程会更好吗?

如何重复线程直到i= ListBox1.Items.Count -1

代码语言:javascript
复制
 var
    lURL : String;
    lResponse : TStringStream;
begin
    lResponse := TStringStream.Create('');
    TestText := Form1.ListBox1.Items[i];
    I := i +1;
    Test1 := Copy(TestText, 0, 16);
    Test2 := Copy(TestText, 18, 3);
    Test3 := Copy(TestText, 22, 2);
    Test4 := Copy(TestText, 27, 2);
 try
     lURL := 'http://www.test.net/test/test.php' +
  '?n=' + Test1 +
  '&m=' + Test2 +
  '&a=' + Test3 +
  '&cv=' + Test4;
     idHttp1.Get(lURL, lResponse);
     lResponse.Position := 0;
     RichEdit1.Lines.LoadFromStream(lResponse);
 finally
     IdHTTP1.Free;
     lResponse.Free();
     if Pos('Bazinga',RichEdit1.Text)> 0 then
     label1.Caption := 'True';
 end;
end;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-14 12:36:28

您可以在一个单独的函数中个性化下载代码,例如:

代码语言:javascript
复制
function DownloadString(AUrl: string): string;
var
  LHttp: TIdHttp;
begin
  LHttp := TIdHTTP.Create;
  try
    LHttp.HandleRedirects := true;
    result := LHttp.Get(AUrl);
  finally
    LHttp.Free;
  end;
end;

然后使用匿名线程获取内容:

代码语言:javascript
复制
procedure TForm3.Button1Click(Sender: TObject);
var
  LUrlArray: TArray<String>;
begin

  // Your URLs are stored in an array of strings
  LUrlArray := form1.listbox1.Items.ToStringArray;

  // This will start an anonymous thread to download the string content from the list of URLs
  TThread.CreateAnonymousThread(
    procedure
    var
      LResult: string;
      LUrl: string;
    begin
      // Fetch each site content from the URL list
      for LUrl in LUrlArray do
      begin
        // DownloadString will be executed asynchronously
        LResult := DownloadString(LUrl);

        // Safely update the GUI using TThread.Synchronize or TThread.Queue
        TThread.Synchronize(nil,
          procedure
          begin
            // Add the resultant string to ???
            // Decide where to set the text to
            memo1.Lines.Text := memo1.Lines.Text + LResult;
          end
        );
      end;
    end
  ).Start;

end;

特别关注GUI更新部分!

如果您使用的是DelphiXE7,那么ITask也可以这样做。

备注1:对于小的内容有效负载很好。如果您下载大量内容或文件,最好使用TStream后代。

注释2:在本例中只有一个线程将下载所有的内容

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27467513

复制
相关文章

相似问题

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