Why this thread raise exception? [duplicate]

久未见 提交于 2019-12-01 13:10:57

问题


i am trying to create a thread in sample project but i got an exception raised here is the sample project code

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. 

when i click on button1 to start creating Thread i stuck with this exception message

First chance exception at $004C0384. Exception class $C0000005 with message 'access violation at 0x004c0384: read of address 0x0000003c'. Process Project1.exe (4060)

and then when i click break its return me to system classes file inside thread create at this code

  FSuspended := not FExternalThread;

what i am doing wrong ? i am using Delphi xe7


回答1:


You should create thread object with
th := TURLDownload.Create('jgvjk', 'ngkj', 'jkgfjk');

Another issues:

In your thread body you call VCL window using showmessage('Reached'); without synchronization. You should not work with VCL staff without some kind of synchronization - use Synchronize or Queue.

reintroduce is not needed for non-virtual constructor

inherited does nothing in Execute



来源:https://stackoverflow.com/questions/36679237/why-this-thread-raise-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!