How do I pause a thread?

I want to draw something. Since the GUI hangs, I want to draw on a thread. But sometimes I want to pause the drawing (for a few minutes).

Delphi documentation says Suspend / resume is deprecated, but does not tell you which functions are replacing them.

Suspend and resume are deprecated. Sleep and SpinWait are clearly not acceptable. I'm amazed to see that Delphi doesn't offer such a basic property / feature.

So how can I pause / resume a thread?

+3


source to share


1 answer


You may need protection fPaused/fEvent

through a critical section. It depends on the specific implementation.



interface

uses
  Classes, SyncObjs;

type
  TMyThread = class(TThread)
  private
    fEvent: TEvent;
    fPaused: Boolean;
    procedure SetPaused(const Value: Boolean);
  protected
    procedure Execute; override;
  public
    constructor Create(const aPaused: Boolean = false);
    destructor Destroy; override;

    property Paused: Boolean read fPaused write SetPaused;
  end;

implementation

constructor TMyThread.Create(const aPaused: Boolean = false);
begin
  fPaused := aPaused;
  fEvent := TEvent.Create(nil, true, not fPaused, '');
  inherited Create(false);
end;

destructor TMyThread.Destroy;
begin
  Terminate;
  fEvent.SetEvent;
  WaitFor;
  fEvent.Free;
  inherited;
end;

procedure TMyThread.Execute;
begin
  while not Terminated do
  begin
    fEvent.WaitFor(INFINITE);
    // todo: your drawings here
  end;
end;

procedure TMyThread.SetPaused(const Value: Boolean);
begin
  if (not Terminated) and (fPaused <> Value) then
  begin
    fPaused := Value;
    if fPaused then
      fEvent.ResetEvent else
      fEvent.SetEvent;
  end;
end;

      

+6


source







All Articles