Delphi file search multithreading

If I execute it like this, my application will not answer until it finds all the files and list them my question: how can I make this multi threded function to avoid the corresponding situation! i'm still 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; 
+6
source share
2 answers

Here you can find an article about the background file scanner implemented using OmniThreadLibrary .

+5
source

You can put the file scan files into a stream, and upon completion, send a Windows message to the main form, which will then update the list window (code not tested, take it as a pseudo-code):

 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; 

You can use it as follows:

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

and in the main form there will be a message handler as follows:

 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; 
+5
source

Source: https://habr.com/ru/post/912065/


All Articles