ICS HTTPCLI免费例外

时间:2012-12-13 15:37:49

标签: delphi delphi-xe2

如果我使用这样的循环制作组件,我怎样才能正确释放组件?如果我像现在一样释放它,我会得到一些GETMEM.INC异常。我是从Indy来的,所以我真的不太了解ICS。

由于

  const
    URLs : array[0..3] of string =
    (
      'http://www.example.com',
      'http://www.example.com',
      'http://www.example.com',
      'http://www.example.com'
    ) ;

    var
      Output: array of TStringList;
      S: array of TMemoryStream;
      Async: array of TSslHttpCli;
    implementation

    procedure RequestDone(Sender: TObject; RqType: THttpRequest;
      ErrCode: Word);
    begin
        with Sender as TSSLHTTPCLI do  begin
          S[Tag].Position:=0;
          Output[Tag].LoadFromStream(S[Tag]);
        end;
      end;


    procedure TForm1.Button1Click(Sender: TObject);
    var
    i:integer;
    begin
        for i := 0 to High(URLS) do begin
           S[i]:=TMemoryStream.Create;
           Output[i]:=TStringList.Create;
           Async[i]:=TSslHttpCli.Create(nil);
           Async[i].Tag:=i;
           Async[i].FollowRelocation:=true;
           Async[i].NoCache:=true;

           Async[i].SocketFamily:=sfAny;
           Async[i].OnRequestDone:=RequestDone;
           Async[i].RcvdStream:=S[i];
           Async[i].URL:= URLs[i];
           Async[i].MultiThreaded:=true;
           Async[i].GetASync;
        end;
    end;

    procedure TForm1.Button4Click(Sender: TObject);
    var
    i:integer;
    begin
        for i := 0 to High(URLS) do begin
           Output[i].Free;
           Async[i].RcvdStream.Free;
           Async[i].Free; // << -- EXCEPTION
           //  S[i].Free;
        end;
    end;

1 个答案:

答案 0 :(得分:2)

您永远不会为ResultAsynchS分配任何内存。你需要SetLength之前,你可以把任何东西放入其中(或取出任何东西)。

procedure TForm1.Button1Click(Sender: TObject);
var
i:integer;
begin
  SetLength(Result, Length(URLS));
  SetLength(S, Length(URLS));
  SetLength(Asynch, Length(URLS));

  for i := 0 to High(URLS) do begin
    S[i]:=TMemoryStream.Create;
    Result[i]:=TStringList.Create;
    Async[i]:=TSslHttpCli.Create(nil);

    // etc.

  end;
end;
BTW,Result是一个变量的可怕名称,尤其是一个全局的变量。它是由编译器自动生成的函数的返回值,并且在函数中的任何地方使用都会使您的代码难以阅读。例如,见:

var
  Result: string = '';

procedure AddToReslt(CharToAdd: Char);
begin
  // Many many lines of code
  // go in here. Maybe a few loops
  // of if statements.
  Result := Result + CharToAdd;
end;

function DoSomeMath: Integer;
begin
  // Some really complex numeric code, maybe
  // calculating the value of `pi` to the 900th
  // digit 
  Result := 2 * 2;
end;

现在很快 - 记住每一个都包含大量代码 - 哪一个是函数,哪个是一个过程?