问题描述
我想画点东西.因为GUI冻结,所以我想画一个线程.但是有时候我想暂停绘图(几分钟).
I want to draw something. Because the GUI freezes I want to draw in a thread. But sometimes I want to pause the drawing (for minutes).
Delphi的文档说,挂起/恢复已过时,但没有说明哪些函数替代了它们.
Delphi's documentation says that Suspend/resume are obsolete but doesn't tell which functions replaces them.
暂不使用Suspend和Resume. Sleep 和SpinWait显然是不合适的.我很惊讶地看到Delphi没有提供这样的基本属性.
Suspend and Resume are deprecated. Sleep and SpinWait are obviously inappropriate. I am amazed to see that Delphi does not offer such a basic property/feature.
那么,如何暂停/恢复线程?
So, how do I pause/resume a thread?
推荐答案
您可能需要通过关键部分进行fPaused/fEvent
保护.这取决于您的具体实现.
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;
这篇关于如何暂停线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!