这是第一次尝试使用Threads,我正在尝试使用Thread复制目录,下面是我所做的工作(在我阅读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.当我单击Button1时,会收到以下错误消息:
无法在运行或挂起的线程上调用Start。
这里怎么了?我对线程不太了解,我甚至试着:
MT := TMyThread.Create('SourceFolder', 'DestinationFolder');发布于 2018-01-31 10:46:53
谢谢大家的帮助和有益的评论:
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.https://stackoverflow.com/questions/48539612
复制相似问题