[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Components and threads question

Posted on 2006-04-25
2
Medium Priority
?
221 Views
Last Modified: 2011-04-14
Hi,

I need to build a Delphi component for my own application that will make recursive search in all hard disk files, so I need to know if it is possible that I build a component which is based on TThread instead of TComponent?

If yes can someone please give me an example of how to define a component which will be based on thread, and if not can someone please tell me the appropriate solution if I want to make the component operations done by a thread.

Thanks in advance for your time
0
Comment
Question by:GiantMatrix
2 Comments
 
LVL 28

Accepted Solution

by:
2266180 earned 1600 total points
ID: 16541363
well, a component must be derived from TComponent. that is impossible to leave out (or it will not be a component anymore) but of course, you can define your thread and put a property in your component. something like:

type TMyThread=class(TThread)
       ...
       end;
       
       TMyThreadedComponent=class(TComponent)
       private
         fThread:TMyThread;
         ...
       public
         ...
       end;

of course, if you want to be able to have more operations in the same time, you will have to dynamically create the threads and not having a property anymore (say the user will start searching on drive c, then anotehr search on drive d (and the search on drive c didn't finish) etc. but since we are talking about one harddrive, it might not be a good idea to let the user have this possibility (it will kill the app ;) ). but in otehr circumstances (say download something) this would be an idea ;)
0
 
LVL 2

Assisted Solution

by:alijunior
alijunior earned 400 total points
ID: 16543003
Look this thread code to delete files over directories:

unit uDeleteThread;

interface

uses
  Classes, SysUtils, ComCtrls, Windows, StdCtrls, Dialogs, Forms;

type
  TDeleteThread = class(TThread)
  private
    pRootFolder : String;
    pFileExt : String;
  protected
    procedure Execute; override;
  public
    procedure Terminated( Sender : TObject );
    constructor Create( const vRootFolder, vFileExt: String);
    destructor Destroy; reintroduce;
  end;

implementation

uses uFileWork, uMainDeleteOldFiles;

//uses uCommom, uWait;

{ TDeleteThread }

constructor TDeleteThread.Create( const vRootFolder, vFileExt: String);
begin
  inherited Create(True);

  pRootFolder := IncludeTrailingPathDelimiter( vRootFolder );
  pFileExt := vFileExt;

  OnTerminate := Terminated;

  Main.pThreadsRunning := Main.pThreadsRunning + 1;

  Resume;

end;

destructor TDeleteThread.Destroy;
begin

  inherited Destroy;
end;

procedure TDeleteThread.Execute;
var Rec : TSearchRec;
    Log : TStringList;
    logFile : String;
    subCount,
    delCount,
    errCount,
    falCount : Integer;
begin
  inherited;

//  if DirectoryExists( pRootFolder ) then
//  try
//    DeleteDir( pRootFolder );
//  except
////    on E : Exception do
//      ShowMessage(pRootFolder);
//  end;
//
//  Exit;

  subCount := 0;
  delCount := 0;
  errCount := 0;
  falCount := 0;

  //Busca subdiretórios no diretório raiz
  if FindFirst (pRootFolder + '*.*', faDirectory, Rec) = 0 then
  try
    repeat
      if ((Rec.Attr and faDirectory) = faDirectory) and (Rec.Name<>'.') and (Rec.Name<>'..') then
      begin
        inc( subCount );
        TDeleteThread.Create( pRootFolder + Rec.Name, pFileExt);
      end;
    until FindNext(Rec) <> 0;
  finally
    SysUtils.FindClose(Rec);
  end;

  //exclui os arquivos aqui
  Log := TStringList.Create;
  Log.Add( 'Data de exclusão dos arquivos:' );
  Log.Add( #9 + FormatDateTime( 'dddd, dd/mm/yyyy hh:nn:ss', Now ) );
  Log.Add( 'Diretório base:' );
  Log.Add( #9 + pRootFolder );
  Log.Add( 'Subdiretórios encontrados:' );
  Log.Add( #9 + IntToStr( subCount ) + ' diretório(s)' );
  Log.Add( 'Máscara para exclusão dos arquivos:' );
  Log.Add( #9 + '*' + pFileExt );
  Log.Add( 'Arquivos excluídos:' );

  if FindFirst (pRootFolder + '*' + pFileExt, faAnyFile - faDirectory, Rec) = 0 then
  try
    repeat
      try

        if Windows.DeleteFile( PChar( pRootFolder + Rec.Name ) ) then
        begin
          Log.Add( #9'OK: ' + Rec.Name );
          inc( delCount );
        end
        else
          begin
            Log.Add( #9'FALHA: ' + Rec.Name );
            inc( falCount );
          end;

        Main.UpdateViewMessage( EmptyStr, 'Excluindo gravação das ' + FormatDateTime('hh:nn:ss', GetDateTimeFromFileName( ChangeFileExt( Rec.Name, EmptyStr ) ) ) );

      except
        on E : Exception do
        begin
          inc( errCount );
          Log.Add( 'ERRO: ' + E.Message + ' (' + Rec.Name + ')' );
        end;
      end;

//      S := TStringList.Create;
//      S.Add( 'Diretorio: ' + pRootFolder );
//      S.Add( 'Arquivo: ' + Rec.Name );
//      S.SaveToFile( pRootFolder + Rec.Name + '.txt' );
//      S.Free;

//      Wait( 'Listando ' + Rec.Name );

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

    Log.Add( 'Sumário:' );
    Log.Add( #9 + 'Arquivos excluídos: ' + IntToStr(delCount) );
    Log.Add( #9 + 'Falhas na exclusão: ' + IntToStr(falCount) );
    Log.Add( #9 + 'Erros encontrados : ' + IntToStr(errCount) );

    logFile := IncludeTrailingPathDelimiter( pRootFolder ) + 'DeleteLog.txt';

//    if subCount = 0 then
//      DeleteDir( ExtractFileDir( logFile ) );

    pRootFolder := ExcludeTrailingPathDelimiter( pRootFolder );

    if DirectoryExists( pRootFolder ) then
      if DeleteDir( pRootFolder ) then
        Log.Add( #9 + 'Diretório "' + pRootFolder + '" excluído com sucesso!' )
      else
        Log.Add( #9 + 'Não foi possível excluir o diretório "' + pRootFolder + '".' );

    logFile := ExtractFilePath( pRootFolder ) +
               'DeleteLog' +
               ExtractFileName( pRootFolder ) +
               '.txt';

    Log.SaveToFile( logFile );

    Log.Free;
  end;

end;

procedure TDeleteThread.Terminated(Sender: TObject);
begin

  Main.pThreadsRunning := Main.pThreadsRunning - 1;

end;

end.



You can do like ciuly to create the thread inside the component. Just replace Main.(...) to MyComponent.(...) or Parent.(...) etc.

You can put a limit of threads created at same time to, like:

repeat

  Application.ProcessMessages;

until pThreadsRunning <= 10;

Best regards...
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Suggested Courses

865 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question