usafethread.pas

来自「一个简单的异常捕获线程!不知道对大家没有作用。 ========== 呵呵 」· PAS 代码 · 共 124 行

PAS
124
字号
// 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 + =
减小字号Ctrl + -
显示快捷键?