Home > Enterprise >  Creating TThread does not enter my Create() method
Creating TThread does not enter my Create() method

Time:09-17

I'm using Delphi Rio. I have created a thread class.

type
  TThreadManager = class(TThread)
    constructor Create;
  end;

constructor TThreadManager.Create;
begin
  inherited Create(True);     // thread-ul va fi creat, dar nu va rula
                               // pentru a-l rula, folosim "Resume" (sau "Execute")
  FreeOnTerminate := True;     // thread-ul va fi distrus automat cand termina
  Priority        := tpNormal; // prioritatea thread-ului este minima
  <- creating internal objects here
  fIsSetupOk      := False;
end;

However (this) constructor is not used when I create the thread in the application. No debug breakpoints are available. And also no objects are created.

threadManager := TThreadManager.Create;
threadManager.Setup(dmMain.ibSessionMain);
threadManager.Resume;

Because of not entering this constructor, an AV is raised when accessing the objects.

Any hints?

Sure, I can create the objects elsewhere (into the setup) but that is not what I want.

CodePudding user response:

TThread has its own parameter-less Create() constructor. You should declare yours as reintroduce to hide the existing one, eg:

type
  TThreadManager = class(TThread)
  public
    constructor Create; reintroduce;
  end;

A better option would be to call Setup() inside of Create() itself, and set CreateSuspended=False. This way, there is no ambiguity over which constructor to call, and the thread will start running automatically after Setup() is finished, eg:

type
  TThreadManager = class(TThread)
  public
    constructor Create(Session: TIB_Session); reintroduce;
  end;

constructor TThreadManager.Create(Session: TIB_Session);
begin
  inherited Create(False);
  FreeOnTerminate := True;
  Priority := tpNormal;
  <- creating internal objects here
  fIsSetupOk := False;
  Setup(Session);
end;

threadManager := TThreadManager.Create(dmMain.ibSessionMain);

Alternatively, you can rename your constructor to something more meaningful, eg:

type
  TThreadManager = class(TThread)
  public
    constructor CreateAndSetup(Session: TIB_Session);
  end;

constructor TThreadManager.CreateAndSetup(Session: TIB_Session);
begin
  inherited Create(False);
  FreeOnTerminate := True;
  Priority := tpNormal;
  <- creating internal objects here
  fIsSetupOk := False;
  Setup(Session);
end;

threadManager := TThreadManager.CreateAndSetup(dmMain.ibSessionMain);

CodePudding user response:

I have found the problem in my code after I use suggestion 2 from remy.
After creating the method as suggested (adding TIB_SESSION as parameter) I have found that the method is not usable because is declared in the protected section not public.
After putting in the correct section all is fine.
Many tks

  • Related