Suspend and Resume is deprecated, so I added two procedures, Pause and UnPause, to the thread.
It seems to work fine, but question is: I dont know if this code is safer than the old way? If it is, could someone tell me why?
Here's how it works: When the Pause procedure is called, the selected thread enters its own critical section. But thats not what pauses the execution. So what happens next is that the threads Execute procedure tries to get into the same critical section (because a Paused flag was set to true in the Pause procedure) but the critical section is already occupied so it can't be entered. Result: the thread sleeps until UnPause is called and the thread "resumes" as before)
Demo attached, and the thread code:
EDIT: removed the callbacks to make it easier to read.
unit uThread;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TMyThread }
TMyThread = class(TThread)
private
FPaused: Boolean;
FCriticalSection: TRTLCriticalSection;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean);
destructor Destroy; override;
procedure Pause;
procedure UnPause;
property Paused: Boolean read FPaused write FPaused;
end;
implementation
uses
Dialogs, Forms;
{ TMyThread }
constructor TMyThread.Create(CreateSuspended: Boolean);
begin
InitCriticalSection(FCriticalSection);
inherited Create(CreateSuspended);
end;
destructor TMyThread.Destroy;
begin
DoneCriticalsection(FCriticalSection);
inherited Destroy;
end;
procedure TMyThread.Pause;
begin
EnterCriticalsection(FCriticalSection);
FPaused:=True;
end;
procedure TMyThread.UnPause;
begin
FPaused:=False;
LeaveCriticalsection(FCriticalSection);
end;
procedure TMyThread.Execute;
begin
repeat
if Terminated then
begin
if FPaused then UnPause;
Break;
end;
..Do some job here...
if FPaused then
EnterCriticalsection(FCriticalSection);
LeaveCriticalsection(FCriticalSection);
Sleep(10);
until False;
end;
end.