How to pause a thread?

时光怂恿深爱的人放手 提交于 2019-12-05 20:25:28

You may need fPaused/fEvent protection via a critical section. It depends on your concrete 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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!