delphi多執行緒檔案複製怎麼實現

沧江魅影發表於2024-08-18

在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方法。執行程式後,點選按鈕即可開始或取消檔案複製操作。同時,窗體的標題欄會實時顯示覆制進度。

注意:在複製大檔案時,可能會導致介面假死。為了避免這種情況,可以考慮在複製過程中使用進度條或者其他方式顯示進度。

相關文章