Thread Completion / Cancellation

I have some objects that when requested, create a thread that uses TIdHTTP to GET or POST to a specified URL. So far this works and using a new thread means the object and main thread can continue on while the operation is being processed or times out.

Now I’d like to add an option for the object owning that thread to change state when the thread is started and change again when it either completes successfully, fails (bad URL format), or times out. Each object has an ID, so would using Synchronize to pass that ID back to the main thread be the way to go?

The other thing that may be required is to cancel a thread that currently waiting on the result of the HTTP GET or POST operation. The object that started it may need to be freed, or the operation aborted before the HTTP timeout occurs. Since the thread has created the TIdHTTP object, what’s the best way for the owner object to kill it off?

Hi David

I would suggest adding a critical section to the owning (Main) object and pass an owner reference to the thread.

Any Functions or properties on the Main Object that need to be accessed by both the main object and the thread object can be then protected by the critical section

Procedure SetThreadState(Val:TThreadstate);
      Do other stuff

One way to Kill off a thread is to set it to free on terminate.

In your case the thread Destructor should wait until the timeout and then free the TIdHttp object as it owns it.

From your main object you set Terminate and then nil the reference;


The thread will free itself when it finally manages to terminate.

Cheers Roger

1 Like

Thanks Roger. I am passing the owner to the thread as I create it, and will look at the other points mentioned. I’m slowly getting the hang of threads.