picture

Threading in Delphi.

Yesterday I had to realize a simple task: Load data from the database into a ComboBox in a separate thread. Threading in Delphi turned out to be quite easy. But still I faced several difficulties, i.e. weird effects. My thread looks pretty simple:


type
  TDataLoaderThread = class(TThread)
    myDBConnection: TADOConnection;
    query1: TADOQuery;
    query2: TADOQuery;
  private
  protected
    procedure InitData;
    procedure Execute; override; 

implementation

procedure TDataLoaderThread.Execute;
begin
  inherited;
  FreeOnTerminate:=True;
  Priority := tpLower;
  Synchronize(InitData);
end;

procedure TDataLoaderThread.InitData();
begin
   // code for retrieving data from the DB
   // and filling the ComboBox of the Form object
end;

I start this thread within my GUI, i.e. Form1. Method InitData is called by means of Synchronize()-method, which allows DataLoaderThread to continue execution in the context of the main thread. InitData sets the items of the ComboBox. Important issues:

1. There should be one DB connection per thread!
2. Calling Form1 by ShowModal blocks DataLoaderThread.
3. Inserting Sleep into DataLoaderThread blocks the main thread, i.e. Form1 for X ms.

Leave a Reply

For spam detection purposes, please copy the number 9270 to the field below: