Delphi
--
Questions
--
Followers
Top Experts
{in Unit1}
var
Form1: TForm1;
th:Threade;
da:boolean;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
da:=true;
end;
procedure TForm1.Button1Click(Sender
begin
th:=Threade.Create(true);
th.Resume;
end;
procedure TForm1.Button2Click(Sender
begin
da:=true;
th.resume;
end;
procedure TForm1.Button3Click(Sender
begin
{this is for pause thread}
da:=false;
end;
{In unit2}
procedure Threade.Execute;
var
i:Integer;
begin
i:=0;
while 1>0 do
begin
inc(i);
form1.label1.Caption:=intt
if not da then break;
end;
if not da then Suspend;
end;
----------
but when i press Button2 my thread terminate
How can i pause and resume my thread.
Zero AI Policy
We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, uMyThread;
type
TForm1 = class(TForm)
ButtonStart: TButton;
ButtonSuspend: TButton;
ButtonResume: TButton;
ButtonTerminate: TButton;
Label1: TLabel;
procedure ButtonStartClick(Sender: TObject);
procedure ButtonResumeClick(Sender: TObject);
procedure ButtonSuspendClick(Sender:
procedure ButtonTerminateClick(Sende
private
{ Private declarations }
myThread : TMyThread;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.ButtonStartClick(Se
begin
myThread := TMyThread.Create(True);
myThread.Resume;
end;
procedure TForm1.ButtonResumeClick(S
begin
myThread.Resume;
end;
procedure TForm1.ButtonSuspendClick(
begin
myThread.Suspend;
end;
procedure TForm1.ButtonTerminateClic
begin
myThread.Terminate;
end;
end.
--------------------------
unit uMyThread;
interface
uses
Classes;
type
TMyThread = class(TThread)
private
{ Private declarations }
i : Integer;
procedure ShowI;
protected
procedure Execute; override;
end;
implementation
uses uQ_21171833, SysUtils;
{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,
Synchronize(UpdateCaption)
and UpdateCaption could look like,
procedure TMyThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ TMyThread }
var
i : Integer;
procedure TMyThread.Execute;
begin
{ Place thread code here }
i := 0;
while not Terminated do
begin
Inc(i);
Synchronize(ShowI);
Sleep(10);
end {WHILE};
end;
procedure TMyThread.ShowI;
begin
Form1.Label1.Caption := IntToStr(i);
end;
end.
{ TMyThread }
var
i : Integer
Delete this unit-level var since "i" is contained within the TMyThread, not the unit.
In unit2}
procedure Threade.Execute;
var
i:Integer;
begin
i:=0;
while 1>0 do
begin
inc(i);
form1.label1.Caption:=intt
if not da then Suspend;
if terminated then
break;
end;
end;






EARN REWARDS FOR ASKING, ANSWERING, AND MORE.
Earn free swag for participating on the platform.
var i:Integer;
begin
i:=0;
while 1>0 do begin
inc(i);
form1.label1.Caption:=intt
if not da then break;
end;
if not da then Suspend;
end;
There's a code formatter at http://www.dow.wau.nl/aew/DelForExp.html which is free and very useful. If you format your code a bit nicer, you would see that after you syspend your thread, you would not execute anything anymore. Thus if you click button2 it will resume the thread and the thread runs out of anything to do thus it ends nicely, just like you told it to do. :-)
I'm not going to comment on your bad code use since I assume you still have a lot to learn. However, a better solution would be this:
procedure Threade.Execute;
var i:Integer;
begin
i:=0;
repeat
inc(i);
form1.label1.Caption:=intt
until terminated;
end;
procedure TForm1.Button3Click(Sender
begin
{this is for pause thread}
th.Suspend.
end;
The repeat-until terminated just increases readability. :-) Terminated is a local thread variable that is set when you call th.Terminate.
Drop that da variable.
Now, another thing... Your thread depends on the form variable, which is not safe practice. If the form gets closed before the thread gets notified about this, the thread will generate an access violation and crash silently. Then again, you won't notice it because the thread crashes SILENTLY. (There's no exception handler in the thread code, and the main thread won't handle exceptions from other threads.) So add a FormClose event and call this code:
TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
th.Terminate; // Tell the thread to stop.
th.WaitFor(Infinity); // Wait until the thread has really stopped.
th.Free;
end;
But since your code is freeing the thread now, you must make a minor change to the thread's constructor.
type
Threade = class(TThread)
private
protected
//blablabla
public
//blablabla
constructor Create; // Don't override this since there's nothing in the parent to override!
end;
constructor Threade.Create;
begin
inherited Create(True); // Creates the thread in suspended mode.
FreeOnTerminate := False; // Prevents the thread from freeing itself.
// Perhaps a resume here if you can add all your initialization code here...
end;
Be aware that most global variables are NOT thread-safe, especially forms and other components. If you want to use global variables or shared resources, you have to learn to use critical sections. Other options that you can use are semaphores, mutexes and events. (Con't confuse Windows events with Delphi events though!) Working with threads is not easy and requires you to think far ahead to consider the possible error-situations you might encounter. Bugs in multi-threaded applications are quite hard to solve, though.
Whenever you change a caption of a component, the component will just send a SetText message to the control below it. This message is then handled in the main thread and processed.
Whenever you call Synchronise to update a caption, the thread sends a message to the main thread so it will execute the synchronise method. It then waits for the main thread to respond back and say it has processed the method. If, in this method all you do is change the caption, it will only result in yet another message being sent to the main thread. The result is still the same, although now you're delaying the thread because it has to wait for more messages to be processed.
As I said before, using threads means that you have to look far, far ahead... Sometimes you can gain a lot of performance while at other times you can avoid bugs if you plan your threads quite well...

Get a FREE t-shirt when you ask your first question.
We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.
So yes, it isn't truly a "MUST" in the strictest sense to use Synchronize in this case, but trying to work without it invites code that is not thread-safe.
Thus, think far, far ahead when you're working with threads. Try to be as familiar as possible with the code you're creating and try to avoid the need of synchronisation since every synchronisation method will cause delays in your application that might be avoided by using a different approach.
I'm just trying to kill a myth here about that you always need to synchronise VCL components. Often you don't, if you know what you're doing! It's only when assignments might start to conflict with one another that you have to use synchronise methods. But better safe than sorry, if you're a beginner. Use it when you're unsure about your code.
I will observe, however, that any code which fails does not perform as well as code which does what it is supposed to do, however much slower. Optimization should be done at a global level through good design rather than at a micro level, tweaking cycles out. Micro-optimization should be done only once a bottleneck has been identified or a design constraint is not being met.
A lot of debate over a 50-pointer! :-)






EARN REWARDS FOR ASKING, ANSWERING, AND MORE.
Earn free swag for participating on the platform.
anyway a realy big No-No that nobody noticed: suspending the thread from itself !!!
actually TThread.Destroy calls Terminate and WaitFor :)

Get a FREE t-shirt when you ask your first question.
We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.
Delphi
--
Questions
--
Followers
Top Experts
Delphi is the most powerful Object Pascal IDE and component library for cross-platform Native App Development with flexible Cloud services and broad IoT connectivity. It provides powerful VCL controls for Windows 10 and enables FMX development for Windows, Mac and Mobile. Delphi is your choice for ultrafast Enterprise Strong Development™. Look for increased memory for large projects, extended multi-monitor support, improved Object Inspector and much more. Delphi is 5x faster for development and deployment across multiple desktop, mobile, cloud and database platforms including 32-bit and 64-bit Windows 10.