Stopping Delphi Indy threads without having to wait end Timeout

后端 未结 2 642
礼貌的吻别
礼貌的吻别 2021-01-01 04:48

It\'s the first time I work on a multi-threads application with Delphi so all is still fesh for me, but I read a lot.

My thread is simple, to be short I just use Ind

2条回答
  •  粉色の甜心
    2021-01-01 05:44

    The class TidHTTP has an OnWork event. Use this event to cancel the data downloading or uploading. How to cancel with this event? Fire an Abort silent exception.

    This is a pseudo code:

    THTTPThread = class(TThread)
        private
            HTTPComponent: TidHTTP;
            procedure OnHTTPProgress(ASender: TObject; AWorkMode: TWorkMode;
                                         AWorkCount: Int64);
        published
            procedure execute();
    end;
    
    implementation
    procedure THTTPThread.execute;
    begin
        Self.HTTPComponent := TidHTTP.Create(nil);
        with HTTPComponent do
        begin
            OnWork := Self.OnHTTPProgress;
            Get('http://www.google.com');
        end;
    end;
    
    procedure THTTPThread.OnHTTPProgress(ASender: TObject; AWorkMode: TWorkMode;
      AWorkCount: Int64);
    begin
    
        if Self.Terminated then
            Abort;
    end;
    

    Take into account that the stages on which OnWork are called are random. The event could be called at the middle of the request, at the begging or even at the end. The code above will work as if you press the stop button on the browser.

    [UPDATE] Forget to mention that if then OnWork event is not called when the Thread is hanged out for a reply of the server, the use can use a timeout if the "last response" was received a specified milliseconds ago. Use GetTickCount for this.

提交回复
热议问题