delphi tcollection
Imagine that your application needs to perform a time-consuming operation (such as an automation server call, saving data to a disk file, exporting data to database server, etc). While your application is busy, user relaxes in the armchair and stupidly looks at display. Is there anyone who likes it? Moreover, Windows do not even redraw an application’s form. You already know how to perform operation simultaneously with threads (if not – see previous articles). Now let’s look to a TThreadComponent – a native VCL component that allows quick and easy threading. The code is written by me and it was tested in several applications.

Component definition.


TThreadComponent = class(TComponent)


    { Public declarations }
    procedure Execute;
    procedure Terminate;
    property Terminated:boolean read GetTerminated;
    property Active:boolean read GetActive;
    constructor Create(AOwner:TComponent);override;
    destructor Destroy;override;


{ Published declarations }
property OnExecution:TNotifyEvent read FOnExecution write FOnExecution;
property OnStartThread:TNotifyEvent read FOnBegThread write FOnBegThread;
property OnFinishThread:TNotifyEvent read FOnEndThread write FOnEndThread;
property Timeout:DWORD read FTimeout write FTimeout default INFINITE;
property UseCoInitialize:boolean read FUseCoInitialize write SetUseCoInitialize;
property Priority:TThreadPriority read FPriority write SetPriority default tpNormal;


Component usage.

Place TThreadComponent on a form. Assign a handler to the onExecute, OnStartThread and OnFinishThread event. Code in those handlers becomes your thread code. Then somewhere in the main thread call Execute method. Execute will not return until thread is terminated or timeout expires. But the Execute method also performs message-handling loop in the context of the caller thread, so the application will continue handle messages and interact with user. OnExecute, OnStartThread and OnFinishThread event handlers will work in the context of newly created thread. The thread will be terminated when the last assigned event handler returns. Call Terminate method to set Terminated property to true. The OnExecute event handler should check value of terminated property and exit if it is set to true. If exception is raised within the OnExecute handler, it will be handled by component’s code and reraised in the context of the main thread. If threaded code works with ActiveX / COM objects set UseCoInitialize property value to True.