The Study

home |  about

Programming

Introduction

Delphi

Java

Projects

Graphics

Introduction

POV-Ray

Terragen

Music

Introduction

Work in Progress

Oddments

Library

Miscellaneous

How to create and use a thread

Back to How to index

Basic steps

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;