【问题标题】:Why this thread raise exception? [duplicate]为什么这个线程会引发异常? [复制]
【发布时间】:2016-04-17 16:38:18
【问题描述】:

我正在尝试在示例项目中创建一个线程,但这里引发了一个异常是示例项目代码

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

type
  TURLDownload = class(TThread)
  private
    FURL: String;
    Fnameofimg: string;
    FPathImage: string;
    FFileNameImage: string;
    // Internal //
    ImageName: string;
    PathURL: string;
  protected
    procedure Execute; override;
  public
    constructor Create(const AUrl: String; Const AOutPathImages: string;
      Anameofimg: String); reintroduce;
    destructor Destroy; override;
    property URL: string read FURL write FURL;
    property PathImage: string read FPathImage;
    property FileNameImage: string read FFileNameImage;
  end;

var
  Form1: TForm1;
  th: TURLDownload;

implementation

{$R *.dfm}
{ TURLDownload }

procedure TURLDownload.reached;
begin
showmessage('done');
end;


    constructor TURLDownload.Create(const AUrl, AOutPathImages: string;
      Anameofimg: String);
    begin
      inherited Create(False);
      FreeOnTerminate := True;
      FURL := AUrl;
      Fnameofimg := Anameofimg;
      FPathImage := AOutPathImages;
    end;

    destructor TURLDownload.Destroy;
    begin

      inherited;
    end;

    procedure TURLDownload.Execute;
    begin
      synchronize(reached);
    end;

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      th.Create('jgvjk', 'ngkj', 'jkgfjk');
    end;

    end. 

当我点击 button1 开始创建线程时,我遇到了这个异常消息

$004C0384 第一次机会例外。异常类 $C0000005 与 消息“0x004c0384 处的访问冲突:读取地址 0x0000003c”。 处理 Project1.exe (4060)

然后当我单击中断时,它会将我返回到在此代码处创建的线程内的系统类文件

  FSuspended := not FExternalThread;

我做错了什么?我正在使用 Delphi xe7

【问题讨论】:

    标签: multithreading delphi delphi-xe7


    【解决方案1】:

    您应该使用
    th := TURLDownload.Create('jgvjk', 'ngkj', 'jkgfjk');

    创建线程对象

    其他问题:

    在您的线程主体中,您使用showmessage('Reached'); 调用VCL 窗口而不进行同步。 你不应该在没有某种同步的情况下与 VCL 员工一起工作 - 使用 Synchronize 或 Queue。

    非虚拟构造函数不需要reintroduce

    inheritedExecute 中什么都不做

    【讨论】:

    • 即使同步也做同样的事情
    猜你喜欢
    • 2016-12-29
    • 2020-03-13
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多