how to run code in background lazarus / 21-General ---------------------------------------------------------------------- rcmz · 2024-01-02 23:43 hi, How can I run code in background? In Delphi I uses TBackgroundWorker Any ideas? TIA rcmz ---------------------------------------------------------------------- cdbc · 2024-01-03 07:07 Hi I think, underneath "TBackgroundWorker" is a thread, sooo use a thread  Regards Benny ---------------------------------------------------------------------- Zvoni · 2024-01-03 07:08 TThread? ---------------------------------------------------------------------- AlanTheBeast · 2024-01-03 15:02 Quote from: Zvoni on January 03, 2024, 08:08:03 amTThread? Without objections, I would do: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Function Achunkofrealpascal (p:pointer):ptrint;VAR   z:somerecord;BEGIN   z := somerecord(p^);   While not z.Shutdown do      begin         stuff;       sleep(z.SleepPeriod);      end;   exit(0);END; //somewhere in main:  With BlockOfData do    begin       Shutdown := false;       SleepPeriod := 100;  //ms       Otherstuff := ...   end;  TID := BeginThread(@Achunkofrealpascal, @Blockofdata); Notes: use flags or data in the referenced record to send signals into/out of the background thread. You can kill the thread using TID as a reference, or (in the case above) by setting Shutdown to true. ---------------------------------------------------------------------- Jiyahana · 2024-01-03 15:16 You can use TThread specifically by creating a descendant of the TThread class. Implement the code that needs to run in the background within the execute method of the TThread descendant. Example. Quoteuses   System.Classes; type   TMyBackgroundThread = class(TThread)   protected     procedure Execute; override;   end; procedure TMyBackgroundThread.Execute; begin   // Perform the background operations here   // Ensure synchronization if accessing UI elements end; Instantiate and start the background thread where needed in your Delphi application. Quotevar   MyThread: TMyBackgroundThread; begin   MyThread := TMyBackgroundThread.Create(True); // Create suspended   MyThread.FreeOnTerminate := True; // Auto-free thread when done   MyThread.Start; // Start the background thread end; I hope example will help. ---------------------------------------------------------------------- Thaddy · 2024-01-03 15:56 Not really. Much easier are the options possible for TThread,ExecuteInThread() ---------------------------------------------------------------------- rcmz · 2024-01-03 17:07 Thx, I will try it. ---------------------------------------------------------------------- KodeZwerg · 2024-01-03 22:42 If its something where you not need to take much care about ... Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure ThreadProc;begin  // all code that needs to run threaded belong in here  Sleep(5000);  Form1.Button1.Enabled := True;end; procedure TForm1.Button1Click(Sender: TObject);var  AProc: TProcedure;begin  Button1.Enabled := False;  AProc := @ThreadProc;  TThread.CreateAnonymousThread(AProc).Start;end;Have in mind, code will run to its endphase even if you closed your process somehow. ---------------------------------------------------------------------- Thaddy · 2024-01-04 09:33 I would still also save the result of the not so anonymous thread, since it returns a valid TThread that can be used later when needed. Comes to mind TThread.CheckTerminated. ---------------------------------------------------------------------- Zvoni · 2024-01-04 09:57 Quote from: Thaddy on January 04, 2024, 10:33:22 amI would still also save the result of the not so anonymous thread, since it returns a valid TThread that can be used later when needed. Comes to mind TThread.CheckTerminated. Nevermind WaitFor and OnTerminated ---------------------------------------------------------------------- CM630 · 2026-02-04 08:33 Quote from: KodeZwerg on January 03, 2024, 11:42:32 pmCode: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure ThreadProc;begin  // all code that needs to run threaded belong in here  Sleep(5000);  Form1.Button1.Enabled := True;end; procedure TForm1.Button1Click(Sender: TObject);var  AProc: TProcedure;begin  Button1.Enabled := False;  AProc := @ThreadProc;  TThread.CreateAnonymousThread(AProc).Start;end;Have in mind, code will run to its endphase even if you closed your process somehow. Can this code be modified in order to pass a parameter to ThreadProc? For example, procedure ThreadProc(Sender: TObject); ---------------------------------------------------------------------- cdbc · 2026-02-04 09:04 Hi Yes, in multiple ways  But I think, the easiest way is to use one of its siblings, namely:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i     Class Function ExecuteInThread(AMethod : TThreadExecuteCallback; AData : Pointer = Nil; AOnTerminate: TNotifyCallBack = Nil) : TThread; overload;static;This class method is /lifted/ from TThread in FPC 3.2.2... With that you get: · a proc to execute in the thread · a 'pointer' param to said procedure - remember 'TObject' is just a pointer... ·· the pointer param, you just typecast to the proper type, first thing in proc. · a callback-proc to execute, when the thread terminates... What more could you ask for?!?  Oh and btw. the 'AData' & 'AOnTerminate' can be nil, without hassle. Try and give that a whirl... Regards Benny Ps.: It's all there in the source, have a good 'looksee' in there... ---------------------------------------------------------------------- CM630 · 2026-02-05 08:17 I did not find examples for ExecuteInThread (except some in delphimode), maybe I should try harder. What I did is: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   TUpdatePortsThread = class(TThread)    private     protected      procedure Execute; override;    public      Owner: TCustomComboBox;    Constructor Create(CreateSuspended : boolean);  end;  ...constructor TUpdatePortsThread.Create(CreateSuspended : boolean);begin  inherited Create(CreateSuspended);  FreeOnTerminate := True;end; procedure TUpdatePortsThread.Execute;begin  try    Application.QueueAsyncCall(@TSerialSelector(Owner).UpdatePorts,0);  finally    Terminate;  end; //tryend; The program crashes, I have a suspicion why it does, but anyway, when it does not crash it hangs until called function is complete  I am wondering if is QueueAsyncCall that hangs my interface, despite using a thread. ---------------------------------------------------------------------- cdbc · 2026-02-05 08:43 Hi I have to run an errin, so if you can wait a little bit, I'll write you an example of use of the above 'ExecuteInThread', when I get back... Otherwise I'll need more info, to be able to help you... Ok? Ps.: Your use of 'QueueAsyncCall' in this situ, defeats the use of a thread, the code you want run, runs in the main thread!!! Not exactly your aim  Regards Benny ---------------------------------------------------------------------- CM630 · 2026-02-05 09:16 Quote from: cdbc on February 05, 2026, 09:43:33 am... I have to run an errin, so if you can wait a little bit, I'll write you an example of use of the above 'ExecuteInThread', when I get back... ... Thanks, waiting a few days (weeks) is not an issue. But if Threads are not a cure, there is no point to write an example (though writing to wiki is usually a good thing). If I do not run the routine with QueueAsyncCall the app crashes (http s://forum.lazarus.freepascal.org/index.php/topic,24490.msg572378.html# msg572378) - sometimes executing one of the lines of the routine takes more than five seconds, when it happens faster, everything is fine. So if threads do not help, what else could I do? Run the routine in a virtual form and somehow signal the main form when the data is ready? Or maybe it I should seek a less impatient WMI query routine. Edit: I made some changes to the WMI caller; it seems to work without asynccall now. I will retry with threads these days.