停止Delphi Indy线程,而不必等待结束超时 [英] Stopping Delphi Indy threads without having to wait end Timeout

查看:326
本文介绍了停止Delphi Indy线程,而不必等待结束超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次使用Delphi在多线程应用程序上工作,所以对于我来说还是很多,但是我读了很多。

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.

我的线程很简单,简而言之,我只是使用Indy(IdHTTP)获取网页的内容,然后验证内容是否包含一个字符串。这里没有问题。

My thread is simple, to be short I just use Indy (IdHTTP) to GET the content of a web page and then I verify if the content contains a string. No problems here.

现在,为了终止线程,我使用带有WHILE DO的布尔值。似乎工作,但这里是问题:像我使用超时与Indy,有时我必须等待超时时间结束之前线程完成(当服务器没有响应)...

Now, to terminate threads I use a boolean with WHILE DO. It seems working but here is the problem : like I use a Timeout with Indy, sometimes I must wait the end of the timeout period before threads finish (when the server is not responding for example)...

这很烦人,特别是当我使用+200线程的时候。与其他软件使用多线程和类似的程序,当我点击停止所有都停止在几秒钟内,这就是我需要的。

It's annoying, especially when I use +200 threads. With other softwares using multi-threads and similar procedure, when I click "Stop" all is stopped in few seconds, and that is what I need.

我读到我应该使用AntiFreeze,以允许IdHTTP读取我的记录...

I read that I should use an AntiFreeze, to allow IdHTTP to "read my instuctions"...

所以,我有点迷失在这里。
我不认为这是非常必要的,但这是我的代码: http://pastebin.com/G7De8bgb

So, I'm a bit lost here. I don't think it's very necessary, but here is my code : http://pastebin.com/G7De8bgb

提前感谢灯:)

Beny

推荐答案

TidHTTP 有一个 OnWork 事件。使用此事件取消数据下载或上传。如何取消此事件? Fire a Abort silent exception。

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.

这是一个伪代码:

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;

考虑到OnWork被调用的阶段是随机的。这个事件可以在请求的中间,在乞讨甚至结束时调用。上面的代码就像在浏览器上按停止按钮一样工作。

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.

[更新]
忘记提到如果当时没有调用OnWork事件线程挂起服务器的回复,如果在指定的毫秒之前收到最后的响应,则使用可以使用超时。为此使用 GetTickCount

这篇关于停止Delphi Indy线程,而不必等待结束超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆