在Delphi中,可以使用TThread類來實現多線程文件復制。以下是一個示例代碼:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TCopyThread = class(TThread)
private
FSourceFile: string;
FDestFile: string;
protected
procedure Execute; override;
public
constructor Create(const SourceFile, DestFile: string);
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
FCopyThread: TCopyThread;
procedure CopyProgress(const BytesCopied, TotalBytes: Int64);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
constructor TCopyThread.Create(const SourceFile, DestFile: string);
begin
inherited Create(True);
FSourceFile := SourceFile;
FDestFile := DestFile;
end;
procedure TCopyThread.Execute;
var
SourceStream, DestStream: TFileStream;
Buffer: array[0..8191] of Byte;
BytesRead, BytesWritten: Integer;
begin
SourceStream := TFileStream.Create(FSourceFile, fmOpenRead or fmShareDenyWrite);
try
DestStream := TFileStream.Create(FDestFile, fmCreate);
try
repeat
BytesRead := SourceStream.Read(Buffer, SizeOf(Buffer));
if BytesRead > 0 then
begin
BytesWritten := DestStream.Write(Buffer, BytesRead);
if BytesWritten <> BytesRead then
Break;
Synchronize(procedure
begin
// 更新進度顯示
Form1.CopyProgress(SourceStream.Position, SourceStream.Size);
end);
end;
until BytesRead = 0;
finally
DestStream.Free;
end;
finally
SourceStream.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if FCopyThread = nil then
begin
FCopyThread := TCopyThread.Create('source.txt', 'dest.txt');
FCopyThread.FreeOnTerminate := True;
FCopyThread.Start;
Button1.Caption := '取消';
end
else
begin
FCopyThread.Terminate;
FCopyThread := nil;
Button1.Caption := '開始';
end;
end;
procedure TForm1.CopyProgress(const BytesCopied, TotalBytes: Int64);
begin
// 更新進度顯示
Caption := Format('Copying %d/%d bytes', [BytesCopied, TotalBytes]);
end;
end.
以上代碼實現了一個簡單的多線程文件復制功能。在按鈕點擊事件中,會創建一個TCopyThread
對象并啟動線程進行文件復制。在TCopyThread.Execute
方法中,會使用TFileStream
讀取源文件內容,并寫入到目標文件中。在每次寫入數據后,通過Synchronize
方法來在主線程中更新進度顯示。
在窗體上放置一個按鈕,并將按鈕的OnClick
事件綁定到Button1Click
方法。運行程序后,點擊按鈕即可開始或取消文件復制操作。同時,窗體的標題欄會實時顯示復制進度。
注意:在復制大文件時,可能會導致界面假死。為了避免這種情況,可以考慮在復制過程中使用進度條或者其他方式顯示進度。