How to use thread Delphi [closed]

一个人想着一个人 提交于 2019-12-03 21:10:46

Here is a threaded example:

type
  TMyThread = class(TThread)
  protected
    procedure Execute; override;
  public:
    ProxyIndex: Integer;
    ProxyServer: String; 
    ProxyPort: TIdPort;
    Url: String;
    ReadTimeout: Integer;
    property ReturnValue;
  end;

procedure TMyThread.Execute;
var
  IdHTTP: TIdHTTP; 
begin 
  if Terminated then Exit;
  IdHTTP := TIdHTTP.Create(nil); 
  try
    IdHTTP.ProxyParams.ProxyServer := ProxyServer; 
    IdHTTP.ProxyParams.ProxyPort := ProxyPort; 
    IdHTTP.ReadTimeout := ReadTimeout;
    IdHTTP.Get(Url);
    ReturnValue := 1;
  finally
    IdHTTP.Free;
  end;
end;

.

var
  CheckingAllProxies: Boolean = False;

procedure TForm1.ThreadTerminated(Sender: TObject);
var
  LThread: TMyThread;
begin
  LThread := TMyThread(Sender);

  ListBox1.Items.Objects[LThread.ProxyIndex] := nil;

  Memo1.Lines.Add(Format('Sıra %d %s', [LThread.ProxyIndex, iif(LThread.ReturnValue = 1, 'Bağlandı.', 'Bağlanamadı.')])); 

  if CheckingAllProxies then
  begin
    if not CheckProxy(LThread.ProxyIndex + 1) then
      CheckingAllProxies := False;
  end;
end;

function TForm1.CheckProxy(ItemIndex: Integer): Boolean; 
var 
  S: String; 
  LThread: TMyThread;
begin 
  Result := False;
  if (ItemIndex < 0) or (ItemIndex >= ListBox1.Items.Count) then Exit;
  if ListBox1.Items.Objects[ItemIndex] <> nil then Exit;
  S := ListBox1.Items[ItemIndex]; 
  LThread := TMyThread.Create(True);
  try
    LThread.ProxyIndex := ItemIndex;
    LThread.ProxyServer := Fetch(S, ':'); 
    LThread.ProxyPort := StrToInt(S); 
    LThread.Url := Edit4.Text;
    LThread.ReadTimeout := StrToInt(ComboBox1.Text);
    LThread.OnTerminate := ThreadTerminated;
    LThread.FreeOnTerminate := True;
    ListBox1.Items.Objects[ItemIndex] := LThread;
  except
    LThread.Free;
    raise;
  end;
  LThread.Resume;
  Result := True;
end; 

procedure TForm1.ListBox1Click(Sender: TObject); 
begin
  if not CheckingAllProxies then
    CheckProxy(ListBox1.ItemIndex);
end;

procedure TForm1.BitBtn2Click(Sender: TObject); 
begin 
  if not CheckingAllProxies then
    CheckingAllProxies := CheckProxy(0);
end; 

procedure TForm1.BitBtn3Click(Sender: TObject); 
begin 
  CheckingAllProxies := False;
end; 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!