Multithreading 由线程引起的Delphi异常类分段(11)?

Multithreading 由线程引起的Delphi异常类分段(11)?,multithreading,delphi,Multithreading,Delphi,当ButtonConnectClick激活时,会出现分段(11)异常。 我认为这是由pocForm1.AddLine('newlinebythread')引起的在线程中,但我不确定如何解决它 这样做的目的是在线程处于活动状态时向备注字段添加行 unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.

当ButtonConnectClick激活时,会出现分段(11)异常。 我认为这是由
pocForm1.AddLine('newlinebythread')引起的在线程中,但我不确定如何解决它

这样做的目的是在线程处于活动状态时向备注字段添加行

unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, FMX.Layouts,
  FMX.Memo, FMX.StdCtrls, IdGlobal, IdIntercept;

type
  TpocForm1 = class(TForm)
    ButtonConnect: TButton;
    ButtonDisconnect: TButton;
    Memo1: TMemo;
    procedure ButtonConnectClick(Sender: TObject);
    procedure ButtonDisconnectClick(Sender: TObject);
    procedure AddLine(text : String);

  private

  public
    { Public declarations }
  end;

  TpocTCPClientThread = class(TThread)
    //TCPClient: TIdTCPClient;
  protected
    procedure Execute; override;
  end;

var
  pocForm1: TpocForm1;

implementation
{$R *.fmx}
var
  thread: TpocTCPClientThread;

procedure TpocForm1.ButtonConnectClick(Sender: TObject);
begin
  Memo1.Lines.Add('Client connected with server');
  thread:= TpocTCPClientThread.Create(False);
end;

procedure TpocForm1.ButtonDisconnectClick(Sender: TObject);
begin
  thread.Terminate;
  thread.WaitFor;
  FreeAndNil(thread);
  Memo1.Lines.Add('Client disconnected from server');
end;

procedure TpocForm1.AddLine(text : String);
begin
  Memo1.Lines.Add(text);
end;


procedure TpocTCPClientThread.Execute();
begin
  while not Terminated do
  begin
    pocForm1.AddLine('new line by thread');
  end;
end;

end.

不能从主线程外部执行GUI代码。您需要确保所有GUI代码都在主线程上执行。例如,通过调用
TThread.Queue
TThread.Synchronize

您不能从主线程外部执行GUI代码。您需要确保所有GUI代码都在主线程上执行。例如,通过调用
TThread.Queue
TThread.Synchronize

使用文件->新建->其他->Delphi项目->Delphi文件->线程对象,然后读取新单元顶部的大注释。您也可以阅读,特别是下面的最后一个要点是使用线程时需要注意的问题和建议。使用文件->新建->其他->德尔福项目->德尔福文件->线程对象,然后阅读新单元顶部的大注释。您还可以阅读,特别是下面的最后一点,即使用线程时要注意的问题和建议。