How to create and use a thread
Basic steps
- Create a new thread class, descending from TThread.
- Include an overriding Execute public procedure.
- In the Execute procedure, write the code for carrying out the thread actions (but see note below about components).
- Create a suspended instance of the new thread, do any set-up, then call Resume to start it running.
Components
If you have to modify or use components in the thread, you MUST call them via the Synchronize method, like so:
Synchronize( MethodWhichUsesComponents() );
Code
Type declaration
type
TMyThread = class(TThread)
public
procedure Execute; override;
end;
Main code
procedure TForm1.StartThread;
begin
{ Create a new thread (suspended), and do any set-up required. }
MyThread := TMyThread.Create(True);
MyThread.FreeOnTerminate := True;
{ Start the thread. }
MyThread.Resume;
end;
procedure TForm1.KillThread;
{ Example of stopping a thread. }
begin
if (MyThread <> nil) and (not MyThread.Terminated) then
begin
{ Tell the thread to terminate }
MyThread.Terminate;
{ Wait until the thread actually terminates (this might not happen
straight away -- depends on what Execute is doing) }
repeat
until MyThread.Terminated;
end;
end;
procedure TMyThread.Execute;
{ This is the main thread procedure -- all the processing for the thread
takes place here. }
begin
while not Terminated do
begin
{ Main thread processing }
end;
end;