1

このコードにスレッドをどのように使用しますか。このコードにより、プログラムはスレッドですばやくロックされます。

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;
4

1 に答える 1

4

次の例のように、別の関数でコードのダウンロードを個別化できます。

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:この場合、1 つのスレッドだけがすべての URL のコンテンツをダウンロードします

于 2014-12-14T12:36:28.947 に答える