multithreading - 如何暂停一个线程?

标签 multithreading delphi bitmap delphi-xe7

我想画点东西。因为 GUI 卡住了,所以我想在线程中绘制。但有时我想暂停绘图(几分钟)。

Delphi 的文档说 Suspend/resume 已过时,但没有说明哪些函数取代了它们。

暂停和恢复已弃用。 Sleep和SpinWait显然是不合适的。我很惊讶地发现 Delphi 没有提供这样的基本属性/功能。

那么,如何暂停/恢复线程?

最佳答案

您可能需要通过关键部分进行fPaused/fEvent保护。这取决于你的具体实现。

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;

关于multithreading - 如何暂停一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44241493/

相关文章:

c# - C++ 位图到 C# 位图

multithreading - Openmp中for循环内的关键部分

c# - 当后台有大量代码时,如何让表单刷新?

Python Win32API 位图.GetBitmapBits()

delphi - 使用 WMI 获取附加信息

delphi - 带有子菜单的Delphi弹出菜单,然后单击项目将执行子菜单中的第一项,可能吗?

android - 320kb 的背景图像大约占用 30MB 的内存空间

c - 多线程素数生成器

c - 我如何测量 C 中每个线程的时间?

delphi - 将基数类型转换为单数