【问题标题】:IdHTTP Get Response ThreadIdHTTP 获取响应线程
【发布时间】:2014-12-14 20:58:22
【问题描述】:

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

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

 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;

【问题讨论】:

标签: multithreading delphi idhttp


【解决方案1】:

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

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;

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

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更新部分!

如果您使用的是 Delphi XE7,ITask 也可以这样做。

注意 1: 这适用于小内容负载。如果您下载大量内容或文件,最好使用 TStream 后代。

注意 2: 在这种情况下,只有一个线程会下载所有 URL 的内容

【讨论】:

  • 如何重复线程直到 i = ListBox1.Items.Count -1?我正在使用 TestText := Form1.ListBox1.Items[i];我:=我+1; Test1 := Copy(TestText, 0, 16); Test2 := Copy(TestText, 18, 3); Test3 := Copy(TestText, 22, 2); Test4 := Copy(TestText, 27, 2);
  • 你没有提到有一个列表框?请先更新您的问题。
  • DownloadString 将阻塞 GUI,直到函数存在!
  • @SolarWind - 是的,但第二个示例显示使用线程来克服 GUI 线程阻塞。
  • @SolarWind 在第二个示例中 DownloadString() 在匿名线程的上下文中被调用,因此它从 GUI 线程自主运行。只有结果显示在主 (GUI) 线程的上下文中。
猜你喜欢
  • 2011-06-25
  • 1970-01-01
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-04
  • 2016-04-06
  • 1970-01-01
相关资源
最近更新 更多