multithreading - delphi 多线程文件搜索

标签 multithreading delphi

如果我像这样执行它,我的应用程序将不会响应,直到找到所有文件并将它们添加到列表框 我的问题是如何使这个函数成为多线程以避免无响应的情况!我还是Delphi新手

procedure TfrMain.FileSearch(const PathName, FileName : string; txtToSearch : string; const InDir : boolean);
var Rec  : TSearchRec;
    Path : string;
    txt  : string;
    fh   : TextFile;
    i    : integer;
begin


Path := IncludeTrailingBackslash(PathName);
if FindFirst(Path + FileName, faAnyFile - faDirectory, Rec) = 0 then
 try
   repeat

     AssignFile(fh, Path + Rec.Name);
     Reset(fh);
     Readln(fh,txt);

     if ContainsStr(txt, txtToSearch) then
        ListBox1.Items.Add(Path + Rec.Name);

   until FindNext(Rec) <> 0;
 finally
   FindClose(Rec);

 end;

If not InDir then Exit;

if FindFirst(Path + '*.*', faDirectory, Rec) = 0 then
 try
   repeat
    if ((Rec.Attr and faDirectory) <> 0)  and (Rec.Name<>'.') and (Rec.Name<>'..') then
     FileSearch(Path + Rec.Name, FileName, txtToSearch, True);
   until FindNext(Rec) <> 0;
 finally
   FindClose(Rec);
 end;
end;

最佳答案

您可以将文件扫描内容放入一个线程中,当工作完成时,向主窗体发送一条 Windows 消息,然后主窗体更新列表框(代码未测试,将其视为伪代码):

const 
  WM_FILESEARCH_FINISHED = WM_USER + 1;

TFileSearchThread = class (TThread)
private
  FPath       : String;
  FFileNames  : TStringList;
protected
  procedure Execute; override;
public
  constructor Create (const Path : String);
  destructor Destroy; override;
  property FileNames : TStrings read FFileNames;
end;

constructor TFileSearchThread.Create (const Path : String);
begin
  inherited Create (True);
  FPath := Path;
  FFileNames := TStringList.Create;
end;

destructor TFileSearchThread.Destroy;
begin
  FreeAndNil (FFileNames);
  inherited;
end;

procedure TFileSearchThread.Execute;  
begin
  // do your file search here, adding each file to FFileNames
  PostMessage (MainForm.Handle, WM_FILESEARCH_FINISHED, 0, 0);
end;

你可以这样使用它:

Thead := TFileSearchThread.Create (Path);
Thread.Start;

主窗体将有一个像这样的消息处理程序:

type
  TMainForm = class(TForm)
    ListBox1: TListBox;
  private
    procedure WMFileSearchFinished (var Msg : TMessage); message WM_FILESEARCH_FINISHED;
  public
    { Public declarations }
  end;

implementation

procedure TMainForm.WMFileSearchFinished (var Msg : TMessage);
begin
  ListBox1.Items.AddStrings (Thread.FileNames);
end;

关于multithreading - delphi 多线程文件搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9946689/

相关文章:

delphi - Win7(Delphi)中将通知区域图标转换为程序图标

c - 我无法将一些 C 代码转换为 Delphi

delphi - 自定义样式 TEdit

c++ - QT多线程和更新GUI

java - 我是否应该创建虚拟对象以便能够同步可能为空的属性?

multithreading - 多重编程,多线程和并行处理?

multithreading - 在多线程代码(通用Lisp)中使用库函数

Java多线程纠错——线程安全单例

Delphi - 预览表单上的 Rave 报告

delphi - 关于德尔福之翼 (ORM)