这是第一次尝试使用Threads
,我正在尝试使用Thread
复制目录,所以这就是我所做的(在我读完之后 {{3 }} ):
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.
当我点击Button1
时,收到以下错误消息:
无法在正在运行或已挂起的线程上调用Start
这里有什么问题?我对线程知之甚少,我甚至尝试过:
MT := TMyThread.Create('SourceFolder', 'DestinationFolder');
答案 0 :(得分:3)
感谢所有人帮助提供有用的评论:
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;
implementation
{$R *.dfm}
{ TMyThread }
constructor TMyThread.Create(const Source, Dest: string);
begin
inherited Create;
Fsource:= Source;
FDest:= Dest;
Self.FreeOnTerminate := True;
end;
destructor TMyThread.Destroy;
begin
inherited;
end;
procedure TMyThread.Execute;
begin
try
TDirectory.Copy(Fsource, FDest);
except on E: Exception do
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var MT: TMyThread;
begin
MT := TMyThread.Create('Source', 'Destination');
end;
end.