User Tools

Site Tools


delphithread

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
delphithread [2024/07/20 17:36] – jwandelphithread [2025/10/10 10:15] (current) – external edit 127.0.0.1
Line 59: Line 59:
 Define a flag in the thread class: Define a flag in the thread class:
 <code> <code>
-type +  type TMyThread = class(TThread) 
-  TMyThread = class(TThread) +     private 
-  private +        FStop: Boolean; 
-    FStop: Boolean; +     protected 
-  protected +        procedure Execute; override; 
-    procedure Execute; override; +     public 
-  public +        procedure Stop;
-    procedure Stop;+
   end;   end;
 </code> </code>
Line 74: Line 73:
 procedure TMyThread.Execute; procedure TMyThread.Execute;
 begin begin
-  while not Terminated and not FStop do +  while not Terminated and not FStop do begin 
-  begin +    // codes here //
-    // Your task code here +
-    Sleep(100); // Simulate work+
   end;   end;
 end; end;
Line 117: Line 114:
 The main form creates the thread with Button1Click and stops it with Button2Click. The main form creates the thread with Button1Click and stops it with Button2Click.
 This approach ensures that the thread can exit gracefully when the Stop method is called.  This approach ensures that the thread can exit gracefully when the Stop method is called. 
 +
 +
 +Another Solution using Timer Event to do some background task:
 +
 +<code>
 +unit BackgroundThread;
 +interface
 +uses Classes, SysUtils;
 +type
 +  TBackgroundProcessThread = class(TThread)
 +  protected
 +    procedure Execute; override;
 +  end;
 +
 +implementation
 +
 +procedure TBackgroundProcessThread.Execute;
 +begin
 +  while not Terminated do begin
 +    // Place your CPU-intensive process here
 +    Sleep(10000); // Simulate a 10-second interval
 +  end;
 +end;
 +
 +end.
 +</code>
 +<code>
 +uses BackgroundThread;
 +
 +procedure TForm1.Timer1Timer(Sender: TObject);
 +var
 +  BackgroundThread: TBackgroundProcessThread;
 +begin
 +  BackgroundThread := TBackgroundProcessThread.Create(True);
 +  BackgroundThread.FreeOnTerminate := True;
 +  BackgroundThread.Start;
 +end;
 +</code>
delphithread.1721496970.txt.gz · Last modified: (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki