1

I tried to make a runtime thread but the thread is behaving strangely, the code has no canvas reference.

procedure TBruteThread.Execute;
var
  j: Integer;
begin
  inherited;
  FreeOnTerminate:=True;
  for j:=1 to StrToInt(Form1.Edit1.Text) do begin
    if Terminated then break;
    Form1.Label2.Caption:=IntToStr(j);
  end;
  Form1.Label2.Caption:='Thread is destroyed';
  Self.Terminate;
end;

enter image description here

Someone have any idea to solve this strange problem?

nkron
  • 19,086
  • 3
  • 39
  • 27
Rafael
  • 3,042
  • 3
  • 20
  • 36

1 Answers1

5

The problem with your code is that it is breaking the VCL threading rules. Access to VCL components must be made from the main thread. Use Synchronise or Queue (methods of TThread) to execute GUI updates on the main thread.

Other comments:

  • Set FreeOnTerminate outside the thread method.
  • Calling Terminate as the final act of the thread method is pointless. The thread is just about to terminate.
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Really, the problem were the unsynchronized method. Thank you. – Rafael Nov 27 '13 at 22:49
  • 2
    Setting `FreeOnTerminate` inside of `Execute()` is perfectly fine and safe. It is not evaluated until after `Execute()` exits. As for calling `Terminate()` at the end of `Execute()`, it can be useful at times, if the `Terminated` property is looked at after `Execute()` exits to know whether `Execute()` exited gracefully or not, especially in older versions that did not have the `FatalException` property. – Remy Lebeau Nov 27 '13 at 22:56
  • @Remy Since the code on the outside needs to know about FreeOnTerminate it mostly makes sense to set it on the outside, in my view. – David Heffernan Nov 27 '13 at 22:59