This is the first time to try working with Threads, I'm trying to copy a directory using a Thread, so here is what I did (After I read this post):
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.IOUtils, System.Types;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TMyThread= class(TThread)
private
Fsource, FDest: String;
protected
public
constructor Create(Const Source, Dest: string);
destructor Destroy; override;
procedure Execute(); override;
published
end;
var
Form1: TForm1;
MT: TMyThread;
implementation
{$R *.dfm}
{ TMyThread }
constructor TMyThread.Create(const Source, Dest: string);
begin
Fsource:= Source;
FDest:= Dest;
end;
destructor TMyThread.Destroy;
begin
inherited;
end;
procedure TMyThread.Execute;
var Dir: TDirectory;
begin
inherited;
try
Dir.Copy(Fsource, FDest);
except on E: Exception do
ShowMessage(E.Message);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
MT := TMyThread.Create('SourceFolder', 'DestinationFolder');
try
MT.Execute;
finally
MT.Free;
end;
end;
end.
When I click on the Button1 I get this error message:
Cannot call Start on a running or suspended thread
What's wrong here? I don't know much about threads,I even try:
MT := TMyThread.Create('SourceFolder', 'DestinationFolder');
Execute. The framework does that. You are just executing it in the main thread. Don't callShowMessagefrom the thread. Can't do GUI outside the main thread.TThread.inheritedin yourExecutesince it overrides an abstract method. And don't declare an variable of typeTDirectory. TheCopymethod is a class method. UseTDirectory.Copy. In case you don't understand @nil's comment, you need to add aninheritedin your thread class constructor.Thread.FreeOnTerminate := True, otherwise you need to keep hold of the reference and destroy it yourself.