Page 1 of 1

Threads in Delphi and Win API functions

PostPosted: January 24th, 2009, 9:34 am
by SaeedShekari
Hi all,
I found that there are a few applications like ‘Process Explorer’ which can show how many threads are running by an application, and they can easily kill any thread and stop it.
I am running a thread among my codes, and all is fine, but when I kill the thread by that Process Explorer, my thread is fully stopped, while my codes assume it as still active, because when I check the thread it shows it as not suspended or not terminated!

I looked into Win32.hlp and I found plenty of API functions working on threads. But I did not find any function which may return the status of a thread like it is killed, terminated or suspended.

Any idea how I can check the status of my thread by Win API functions?
Below is my code in brief:
Code: Select all
TMyThread = class(TThread)
  procedure Execute; override;
end;

procedure TMyThread .Execute;
Begin
  While True Do; // A Never Ending Loop just for test
End;

Form1 = class(TForm)
  …
  Private
    MyThread: TMyThread;
    Procedure MyFunction;
  …
End;

Procedure Form1.MyFunction;
Begin
  MyThread:= TMyThread.Create(True);
  MyThread.Priority:= tpLower;
  MyThread.Resume;
End;

Before killing MyThread, I go to MyThread Execute procedure and put a break point there, and it stopps, but After killing it, I put the break point, it does not stop, which means it has been suspended or terminated.
in below I have attached how Process Explorer can kill my thread.


Re: Threads in Delphi and Win API functions

PostPosted: January 24th, 2009, 11:38 am
by Kambiz
Killing a thread or process is not a good idea. It may put the application in an unstable situation and cause memory/resource leak.

Anyway, both Terminated and Suspended properties of Delphi are wrappers around Boolean variables, because it was supposed nobody is going to kill the thread.

You can use any Windows thread query API to know whether your thread handle is valid.

Re: Threads in Delphi and Win API functions

PostPosted: January 24th, 2009, 12:26 pm
by SaeedShekari
Hi Kambiz,

As you advised, I simply used GetThreadTimes API function and now I can monitor my thread. The ExitTime value is set to non zero by that function soon the thread is killed.

Thanks