delphi文件搜索多线程

时间:2012-03-30 16:13:18

标签: multithreading delphi

如果我执行它,我的应用程序将不会响应,直到找到所有文件和它们到列表框 我的问题是如何使这个功能多线程,以避免不相应的情况!我仍然是Delphi novoice

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;

2 个答案:

答案 0 :(得分:5)

Here您可以找到有关使用OmniThreadLibrary实施的后台文件扫描程序的文章。

答案 1 :(得分:5)

您可以将文件扫描内容放入线程中,当工作完成后,向主窗体发送一条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;