RAD Studio |  |

Defining Thread Objects
See Also
Collapse All

For most applications, you can use a thread object to represent an execution thread in your application. Thread objects simplify writing multi-threaded applications by encapsulating the most commonly needed uses of threads.

Note: Thread objects do not allow you to control the security attributes or stack size of your threads. If you need to control these, you must use the BeginThread function. Even when using BeginThread, you can still benefit from some of the thread synchronization objects and methods described in Coordinating Threads.
To use a thread object in your application

1. Create a new descendant of TThread, choose FileNewOther from the main menu.
2. In the New Items dialog box under Delphi Files, double-click Thread Object and enter a class name, such as TMyThread.
3. Check the Named Thread check box and enter a thread name (VCL applications only).
4. Click OK, the Code Editor creates a new unit file to implement the thread.

For more information on naming threads, see Naming a Thread.
Note: Unlike most dialog boxes in the IDE that require a class name, the New Thread Object dialog box does not automatically prepend a 'T' to the front of the class name you provide.
The automatically generated unit file contains the skeleton code for your new thread class. If you named your thread TMyThread, it would look like the following:
Copy Code

    unit Unit2;
    interface
    uses
    Classes;
    type
    TMyThread = class(TThread)
    private
    { Private declarations }
    protected
    procedure Execute; override;
    end;
    implementation
    { TMyThread }
    procedure TMyThread.Execute;
    begin
    { Place thread code here }
    end;
    end.

Copy Code

    //---------------------------------------------------------------------------
    #include <vcl.h>
    #pragma hdrstop
    #include "Unit2.h"
    #pragma package(smart_init)
    //---------------------------------------------------------------------------
    __fastcall TMyThread::TMyThread(bool CreateSuspended): TThread(CreateSuspended)
    {
    }
    //---------------------------------------------------------------------------
    void __fastcall TMyThread::Execute()
    {
    // ---- Place thread code here ----
    }
    //---------------------------------------------------------------------------

In the automatically generated unit file, you

- Optionally, initialize the thread.
- Write the thread function by filling in the Execute method.
- Optionally, write clean-up code.

See Also

Executing Thread Objects

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!