0

当我尝试使用此线程时,我不断收到“线程错误:句柄无效 (6)”,但我看不到问题。可以的话请帮忙,谢谢!

stackoverlow 抱怨我解释得不够充分。所以,我创建了一个线程类,它编译时没有任何错误,但是当我用执行调用它时,它似乎运行正常,但在析构函数中抛出了这个错误。

  tdownloadthread = class(tthread)
    private
      furl,
      ffilename,
      fmsg: string;
      fdl: tidhttp;
      readings,bpstotal,avgbps: int64;
      fpercent: word;
      fsuccess,fcanceled: boolean;
      start: tdatetime;
      fspeed,fremaining: string;
    public
      constructor create(url,filename: string);
      destructor destroy; override;
      procedure execute; override;
      procedure DlWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
      procedure cancel;

      property success: boolean read fsuccess;
      property canceled: boolean read fcanceled;
      property speed: string read fspeed;
      property percent: word read fpercent;
      property remaining: string read fremaining;
      property msg: string read fmsg;
  end;


constructor tdownloadthread.create(url,filename: string);
begin
  fsuccess:=false;
  fcanceled:=false;

  fdl:=tidhttp.Create(nil);
  fdl.OnWork:=dlwork;
  fdl.HandleRedirects:=true;

  furl:=url;
  ffilename:=filename;

  freeonterminate:=false;
end;

destructor tdownloadthread.Destroy;
begin
  fdl.Free;
end;

procedure tdownloadthread.cancel;
begin
  fdl.Disconnect;
  fcanceled:=true;
end;

procedure tdownloadthread.DlWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
var
  Http: TIdHTTP;
  ContentLength: Int64;
  i,h,m,esec,sec,rsec,bps: Integer;
  f: tdatetime;
begin
  Http := TIdHTTP(ASender);
  ContentLength := Http.Response.ContentLength;

  if (Pos('chunked', LowerCase(Http.Response.ResponseText)) = 0) and
     (ContentLength > 0) then
  begin
    fpercent := trunc(100*(AWorkCount / ContentLength));

    esec := secondsbetween(now, start);

    if (avgbps > 0) then
     begin
       i:=contentlength div avgbps;
       f:=incsecond(now, i);
       rsec:=secondsbetween(now, f);

       sec:=rsec - esec;

       h:=sec div 3600;
       m:=sec div 60 - H * 60;
       sec:=sec - (H * 3600 + M * 60) ;
    end;

    if (esec > 0) then
      bps:=(aworkcount div esec)
       else
      bps:=0;

    inc(readings);
    inc(bpstotal, bps);
    avgbps:=bpstotal div readings;

    if (avgbps / 1024 < 1024) then
      fspeed:=format('%2f KB/s', [avgbps / 1024])
       else
      fspeed:=format('%2f MB/s', [(avgbps div 1024) / 1024]);

    fremaining:=format('%s m %s s', [zero(m), zero(secno)]);
  end;
end;

procedure tdownloadthread.Execute;
var fn,cd: string;
    data: tmemorystream;
begin
  try
    start:=now;

    data:=tmemorystream.Create;

    fdl.Get(furl, data);
    cd:=fdl.Response.ContentDisposition;
    if (pos('filename=', cd) > 0) then
      fn:=extractfilepath(paramstr(0))+copy(cd, pos('=', cd)+1, length(cd))
         else
      fn:=ffilename;
    data.SaveToFile(fn);
    ffilename:=fn;
    fsuccess:=true;

    data.Free;
  except
    on e: exception do
      begin
        fsuccess:=false;
        fmsg:=e.Message;
      end;
  end;
end;

procedure testdownload;
var downloadthread: tdownloadthread;
begin
  downloadthread:=tdownloadthread.create('http://www.someurl.com/filename.old',extractfilepath(paramstr(0))+'filename.new');
  downloadthread.Execute;
  if downloadthread.canceled then showmessage('canceled');
  if downloadthread.success then showmessage('success');
  if not downloadthread.success then showmessage('error: '+downloadthread.msg);
  downloadthread.Free;
end;
4

1 回答 1

4

您忘记为 TThread 调用继承的 ctor:

constructor tdownloadthread.create(url,filename: string);
begin
  inherited create(true); // construct TThread
  fsuccess:=false;
  fcanceled:=false;

  fdl:=tidhttp.Create(nil);
  fdl.OnWork:=dlwork;
  fdl.HandleRedirects:=true;

  furl:=url;
  ffilename:=filename;

  freeonterminate:=false;
  resume; // actually run thread
end;

此外,正如@LU RD 所指出的,无需直接调用 TThread 实例的 Execute() 方法 - 线程由操作系统直接执行。

至于释放它,有一些选择。按优先顺序:

1)根本不要释放它。如果您打算在应用程序运行期间进行多次下载,请将线程循环到生产者-消费者队列弹出,以便可以重新使用该线程来下载更多文件,而无需尝试释放它。

2) 在 try/finally 中释放其内部资源(例如 TidHTTP 实例)后,让线程实例释放自身(freeOnTerminate=true)。

-999999) 使用 OnTerminate 处理程序或任何其他可怕的 Delphi TThread 东西,如 TThread.WaitFor。

于 2012-11-05T17:41:15.953 回答