gpt4 book ai didi

multithreading - 使用Delphi TThread

转载 作者:行者123 更新时间:2023-12-03 18:30:04 27 4
gpt4 key购买 nike

这是第一次尝试使用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时,出现以下错误消息:

Cannot call Start on a running or suspended thread



怎么了我对线程了解不多,甚至尝试:
MT := TMyThread.Create('SourceFolder', 'DestinationFolder');

最佳答案

谢谢大家对有用的评论提供帮助:

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.

关于multithreading - 使用Delphi TThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48539612/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com