Hello there. I starting delphi ( free pascal ), I have confused how to doing background worker in delphi and this what I found this solution.
This for unfreezing UI when executing long task.
Add this before after type
PHP Code:
// =========== WORKER CLASS
TMyWorkerThread = class(TThread)
protected
// the main body of the thread
procedure Execute; override;
end;
// =========== WORKER CLASS
then add this after implementation
PHP Code:
procedure TMyWorkerThread.Execute;
var
i : integer;
begin
i := 0;
while i < 100 do
begin
// play beep sound
Form1.Label1.Caption := IntToStr(i);
sleep(100); //refreshing cpu -- around 16 miliseconds
// process pending messages might be in message queue
i:= i +1;
//Application.ProcessMessages;
end;
//Here we do work
//showmessage('aaaaaaaaaa');
//When we exit the procedure, the thread ends.
//So we don't exit until we're done.
end;
And called it when button click or else
PHP Code:
TMyWorkerThread.Create(false);
FULL CODE
FULLCODE
PHP Code:
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
// =========== WORKER CLASS
TMyWorkerThread = class(TThread)
protected
// the main body of the thread
procedure Execute; override;
end;
// =========== WORKER CLASS
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
procedure TMyWorkerThread.Execute;
var
i : integer;
begin
i := 0;
while i < 100 do
begin
// play beep sound
Form1.Label1.Caption := IntToStr(i);
sleep(100); //refreshing cpu -- around 16 miliseconds
// process pending messages might be in message queue
i:= i +1;
//Application.ProcessMessages;
end;
//Here we do work
//showmessage('aaaaaaaaaa');
//When we exit the procedure, the thread ends.
//So we don't exit until we're done.
end;
{$R *.lfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
begin
TMyWorkerThread.Create(false);
end;
end.