📄 usafethread.pas
字号:
// Author: 吴成敏 memkey@gmail.com
// Time: 2008.5.28
unit uSafeThread;
interface
uses
SysUtils,Classes;
type
TSafeThread = class(TComponent)
private
FActive: Boolean;
FOnExecute: TNotifyEvent;
FOnExecuteError: TNotifyEvent;
FThread: TThread;
procedure SetActive(const Value: Boolean);
procedure SetOnExecute(const Value: TNotifyEvent);
procedure SetOnExecuteError(const Value: TNotifyEvent);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Active: Boolean read FActive write SetActive;
property OnExecute: TNotifyEvent read FOnExecute write SetOnExecute;
property OnExecuteError: TNotifyEvent read FOnExecuteError write
SetOnExecuteError;
end;
procedure Register;
implementation
{ This procedure is used to register this component on the component palette }
procedure Register;
begin
RegisterComponents('GoFar', [TSafeThread]);
end;
{ TInnerSafeThread }
type
TInnerSafeThread = class(TThread)
private
FOnExecuteError: TNotifyEvent;
FOnExecute: TNotifyEvent;
{ Private declarations }
protected
procedure DoExecute;
procedure DoExecuteError;
procedure Execute; override;
public
property OnExecute: TNotifyEvent read FOnExecute write FOnExecute;
property OnExecuteError: TNotifyEvent read FOnExecuteError write
FOnExecuteError;
published
end;
procedure TInnerSafeThread.DoExecute;
begin
if Assigned(FOnExecute) then
FOnExecute(Self);
end;
procedure TInnerSafeThread.DoExecuteError;
begin
if Assigned(FOnExecuteError) then
FOnExecuteError(Self);
end;
procedure TInnerSafeThread.Execute;
begin
try
while not Terminated do
begin
Synchronize(DoExecute);
end;
except
Synchronize(DoExecuteError);
end;
end;
{TSafeThread}
constructor TSafeThread.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FThread := TInnerSafeThread.Create(True);
end;
destructor TSafeThread.Destroy;
begin
FreeAndNil(FThread);
inherited Destroy;
end;
procedure TSafeThread.SetActive(const Value: Boolean);
begin
if Value<>FActive then
begin
FActive := Value;
if Factive then
FThread.Resume
else
FThread.Terminate;
end;
end;
procedure TSafeThread.SetOnExecute(const Value: TNotifyEvent);
begin
FOnExecute := Value;
TInnerSafeThread(FThread).OnExecute:= FOnExecute;
end;
procedure TSafeThread.SetOnExecuteError(const Value: TNotifyEvent);
begin
FOnExecuteError := Value;
TInnerSafeThread(FThread).OnExecuteError:= FOnExecuteError;
end;
end.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -