0

I made a basic class design to work in multi threads with ADO / MSSQL database The complete class design is here

the basic thread code goes like this :

constructor PaintBitmapThread.Create(bmp_width, bmp_height: Integer;
  server, databasename, tablename, sqlstr: String; ThreadId: Integer);
begin
    FBitmap  :=TBitmap.create;
    FBitmap.Width := bmp_width;
    FBitmap.Height := bmp_height;
    FBitmap.PixelFormat := pf24bit;

    FConnection :=TAdoConnection.Create(nil);
    fserver := server;
    fdatabasename := databasename;
    ftablename  := tablename;

    FConnection.LoginPrompt := false;
    ConnecttoDatabase(fserver, fdatabasename, FConnection)

end;

destructor PaintBitmapThread.destroy;
begin
   FBitmap.Free;
   FConnection.Free;
  inherited;
end;

procedure PaintBitmapThread.Execute;
 var
   ThreadQuery : TADOQuery;
   k : integer;
 begin
   inherited;

   CoInitialize(nil) ; //CoInitialize was not called

   ThreadQuery := TADOQuery.Create(nil) ;
   try
// ADO DB THREAD MUST USE OWN CONNECTION
     ThreadQuery.Connection := FConnection;
     ThreadQuery.CursorLocation := clUseServer;
     ThreadQuery.LockType := ltReadOnly;
     ThreadQuery.CursorType := ctOpenForwardOnly;
     ThreadQuery.SQL.Text := FSQLStr;

     ThreadQuery.Open;
     while NOT ThreadQuery.Eof and NOT Terminated do
        begin



       //Canvas Does NOT Allow Drawing if not called through Synchronize
       //Synchronize(RefreshCount) ;

        ThreadQuery.Next;
       end;
   finally
     ThreadQuery.Free;
   end;

   CoUninitialize()
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
     fserver := 'localhost\sqlexpress';
     fdatabase := 'test_wbbugfix';
     ftable := 'obj';

     ServerEdit.Text := fserver;
     DatabaseEdit.Text := fdatabase;
     TableEdit.Text := ftable
end;

Before leaving the thread.create constructor I get an AV like the screen dump below enter image description here,

what is wrong with my code ???

Community
  • 1
  • 1
user1769184
  • 1,571
  • 1
  • 19
  • 44
  • As pointed out in your previous question, I fail to see what performance improvements you are trying to achieve here... – whosrdaddy Jun 19 '14 at 14:29

1 Answers1

4

The error message states what is the problem here. You are creating the thread with the CreateSuspended parameter set to False. This means that the thread will start immediately after calling the constructor. Any call to Start will lead to this exception.

Solution

Create the thread with the CreateSuspended flag set to True. Now you can start the thread calling the Start method.

Besides this problem, I would like to point out that your TADOConnection and TADOQuery do not live on the same thread. This is because the PaintBitmapThread constructor is executed in the context of the thread that creates the PaintBitmapThread thread object. You can solve this problem by moving the connection construction code inside the Execute method.

whosrdaddy
  • 11,720
  • 4
  • 50
  • 99