首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用德尔菲TThread

使用德尔菲TThread
EN

Stack Overflow用户
提问于 2018-01-31 10:15:17
回答 1查看 6.6K关注 0票数 2

这是第一次尝试使用Threads,我正在尝试使用Thread复制目录,下面是我所做的工作(在我阅读this post之后):

代码语言:javascript
复制
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。

这里怎么了?我对线程不太了解,我甚至试着:

代码语言:javascript
复制
MT := TMyThread.Create('SourceFolder', 'DestinationFolder');
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-31 10:46:53

谢谢大家的帮助和有益的评论:

代码语言:javascript
复制
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.
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48539612

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档