我想画点东西。因为 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/