user10699450
user10699450

Reputation:

Why is the code in the thread executed twice?

As indicated in the title, why is the following code executed twice (2x Test in the console) and how to fix it?

type
  TSelfThread = class(TThread)
    procedure Execute; override;
end;

procedure TSelfThread.Execute;
begin
  Writeln('Test');
end;

var
  SelfThread : TSelfThread;
begin
  try
    SelfThread := TSelfThread.Create(False);
  except
    on E: Exception do
      Writeln('Error');
  end;
end.

Upvotes: 1

Views: 329

Answers (1)

David Heffernan
David Heffernan

Reputation: 612954

The only possible explanation for this behaviour is the bug in your code where you fail to wait for the thread to complete before terminating the process.

Change the code to be like this:

SelfThread := TSelfThread.Create(False);
SelfThread.WaitFor;

Upvotes: 2

Related Questions