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

时间:2015-02-17 16:11:57

标签: multithreading delphi

当ButtonConnectClick被激活时,它会给出Segmentation(11)异常。 我认为它是由线程中的pocForm1.AddLine('new line by thread');引起的,但我不确定如何解决它。

这个想法是在线程处于活动状态时在备注字段中添加行。

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.

1 个答案:

答案 0 :(得分:6)

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