Defining the Thread Object

From RAD Studio
Jump to: navigation, search

Go Up to Building a Multithreaded Application


To define the thread object

  1. Choose File > New > Other, click Individual Files under Delphi, and double-click the Thread Object icon.
  2. Enter a class name, for example, TMyThread.
  3. Optionally check the Named Thread check box, and enter a name for the thread, for example, MyThreadName.

    Tip: Entering a name for Named Thread makes it easier to track the thread while debugging.

  4. Click OK.

The Code Editor displays the skeleton code for the thread object.

The code generated for the new unit will look like this if you named your thread class TMyThread:

 unit Unit1;
 
 interface
 
 uses
   Classes;
 
 type
   TMyThread = class(TThread)
   private
     { Private declarations }
   protected
     procedure Execute; override;
   end;
 
 implementation
 
 { Important: Methods and properties of objects in visual components can only be
   used in a method called using Synchronize, for example,
 
       Synchronize(UpdateCaption);
 
   and UpdateCaption could look like,
 
     procedure TMyThread.UpdateCaption;
     begin
       Form1.Caption := 'Updated in a thread';
     end; }
 
 { TMyThread }
 
 procedure TMyThread.Execute;
 begin
   { Place thread code here }
 end;
 
 end.

Adding a name for the thread adds a call of the TThread class method NameThreadForDebugging to the TThread Execute procedure:

 unit Unit1;
 
 interface
 
 uses
   Classes;
 
 type
   TMyThread = class(TThread)
   private
     { Private declarations }
   protected
     procedure Execute; override;
   end;
 
 implementation
 
 { Important: Methods and properties of objects in visual components can only be
   used in a method called using Synchronize, for example,
 
       Synchronize(UpdateCaption);
 
   and UpdateCaption could look like,
 
     procedure TMyThread.UpdateCaption;
     begin
       Form1.Caption := 'Updated in a thread';
     end; }
 
 { TMyThread }
 
 procedure TMyThread.Execute;
 begin
   NameThreadForDebugging('My Cool Thread');
   { Place thread code here }
 end;
 
 end.
 // Unit1.cpp
 #include "Unit3.h"
 #pragma package(smart_init)

 //   Important: Methods and properties of objects in VCL can only be
 //   used in a method called using Synchronize, for example:
 //
 //      Synchronize(&UpdateCaption);
 //
 //   where UpdateCaption could look like:
 //
 //      void __fastcall mythread::UpdateCaption()
 //      {
 //        Form1->Caption = "Updated in a thread";
 //      }

 __fastcall TMyThread::TMyThread(bool CreateSuspended)
	: TThread(CreateSuspended)
 {
 }

 void __fastcall TMyThread::Execute()
 {
	TThread::NameThreadForDebugging("My Cool Thread");
	//---- Place thread code here ----
 }

See Also