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/23 15:32] – jwandelphithread [2025/10/10 10:15] (current) – external edit 127.0.0.1
Line 73: 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 116: 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.1721748723.txt.gz · Last modified: (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki