简体   繁体   English

TThread 块 窗体线程

[英]TThread blocks Form thread

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).而且我不知道为什么在单击按钮后新线程阻塞了 GUI(主线程)。 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.我很抱歉这个愚蠢的问题,但我已经在这个基本的事情上花了几个小时,而且我是 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;    

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;  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM