TThread blocks Form thread

405 views Asked by At

This is absolutely basic code for testing purpose. And I can't find out why after clicking the button the new thread is blocking the GUI ( Main thread). Is there any reason for this behavior to happen? I'm sorry for silly question, but I've spend hours on this basic thing and I'm a beginner with FPC.

{$mode objfpc}{$H+}
interface
uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;

type
  { TForm1 }
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    Memo1 : Tmemo;
    procedure Button1Click(Sender: TObject);
    procedure FormActivate(Sender: TObject);
  end;

type
  TMemoThr = class(TThread)
      procedure Execute; override;
      Constructor Create(CreateSuspended : boolean);
  end;

  var
  Form1: TForm1;
  M :TMemoThr;

implementation
{$R *.lfm}
constructor TMemoThr.Create(CreateSuspended : boolean);
begin
  inherited Create(CreateSuspended);
  FreeOnTerminate := True;
end;

procedure TMemoThr.Execute();
begin
      while (not Terminated) do begin
            self.sleep(5000);  // this should only put thread to sleep, not entire Form
            showMessage('Inside');
      end;
end;

procedure TForm1.FormActivate(Sender: TObject);
begin
     M := TMemoThr.Create(false);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
         M.Execute;
end;    
1

There are 1 answers

0
GeneCode On

Here my Thread code:

  { TMainPortThread }
  TMainPortThread = class(TThread)
  private
    procedure Synchronous;
  protected
    procedure Execute; override;
  public
  end; 

Execute procedure:

procedure TMainPortThread.Execute;
var
  i:integer;
begin
  while true do begin
        // do your stuff
  end;
end; 

Start Thread:

procedure TForm1.Button2Click(Sender: TObject);
begin
     TMainPortThread.Create(false);
end;