Re: Disconnect TIdHttp in thread

Giganews Newsgroups
Subject:Re: Disconnect TIdHttp in thread
Posted by: Karsten (…@mail.com)
Date:Wed, 27 Jul 2005

> See 6 :)

Excellent post, I definitly want to keep a copy of this :-)

I have one thing though. I see one problem with using FreeOnTerminate, it's
a bit difficult to get it right ;)

I have this thread that should work, leaving the result in a property for me
and notify me when it's done using postmessage.

Does this example seems ok to you?

TMyThread = class(TThread)
private
    ThreadFinished: Boolean;    //Has thread stopped working
    CS: TRTLCriticalSection;    //Use CS to not risking setting
FreeOnTerminate after thread has stopped
    hEvent: THandle;            //Use event to signal that thread work is
done, check ResultValid
    WorkIn: X;                  //Work to thread
    WorkOut: X;                //Work by thread
protected
    procedure Execute; override;
public
    constructor Create;                        //Called by thread#1
    destructor Destroy; override;              //Called by thread#1
    function GetWork(in.. out..): Boolean;      //Called by thread#1
    procedure Cancel;      //Called by thread#2 to allow thread#1 one to
continue and do some finalization
end;

constructor TMyThread.Create;
begin
    inherited Create(True);
    InitializeCriticalSection(CS);
    hEvent := CreateEvent(nil, False, False, nil);
end;

destructor TMyThread.Destroy;
begin
    //Call to destructor made either explicitly to Free or implicitly by
FreeOnTerminate
    //If thread hasn't finished don't wait for it to finish, but set
FreeOnTerminate and forget about it
    EnterCriticalSection(CS);
    try
        if not ThreadFinished then
        begin
            FreeOnTerminate := True;
            Exit;  //Don't free anything, but simply flag the thread to
free it self
        end;
    finally
        LeaveCriticalSection(CS);
    end;

    DeleteCriticalSection(CS);
    CloseHandle(hEvent);
    inherited;
end;

function TMyThread.GetWork(in.. out..): Boolean;
begin
    WorkIn := ...
    Resume;
    WaitForSingleObject(hEvent, INFINITE);
    out := WorkOut;
    Result := WorkOut = ...;
end;

procedure TMyThread.Cancel;
begin
    Terminate;
    SetEvent(hEvent);
end;

procedure TMyThread.Execute;
begin
    if not Terminated then
        WorkOut := DoWork!
    SetEvent(hEvent);

    EnterCriticalSection(CS);
    try
        ThreadFinished := True;
    finally
        LeaveCriticalSection(CS);
    end;
end;

Replies

None

In response to

Re: Disconnect TIdHttp in thread posted by Martin James on Wed, 27 Jul 2005