event



CoreShell: TCoreShell;








CoreShell := TCoreShell.Create(...);




CoreShell.InitializeApplication_1;


CoreShell.InitializeApplication_2;




......


CoreShell.ExitApplication;
CoreShell.Free;








TTaskThread = class;


TCoreShell = class(TObject)
private
  FApplicationCloseEvent: THandle;
  FTaskThreadExitEvent: THandle;
  FTaskThread: TTaskThread;
public
  function InitializeApplication: Boolean;
  procedure ExitApplication;
end;




TTaskThread = class(TThread)
private
  FApplicationCloseEvent: THandle;
  FThreadExitEvent: THandle;
protected
  procedure Execute; override;
public
  constructor Create(CloseEvent: THandle; ExitEvent: THandle);
end;








constructor TTaskThread.Create(CloseEvent: THandle; ExitEvent: THandle);
begin
  FApplicationCloseEvent := CloseEvent;
  FThreadExitEvent := CloseEvent;


  inherited Create(False);
end;






procedure TTaskThread.Execute;
begin
  if FThreadExitEvent <> 0 then
  begin
    ResetEvent(FThreadExitEvent);
  end;


  try
    while not Terminated do
    begin
      if WaitForSingleObject(FApplicationCloseEvent, 0) = WAIT_OBJECT_0 then
      begin
        Break;
      end;


      ......




      Sleep(1000);
    end;
  except
    // record ThreadError
    on E: Exception do
    begin
      //E.Message
    end;
  end;


  if FThreadExitEvent <> 0 then
  begin
    SetEvent(FThreadExitEvent);
  end;
end;










function TCoreShell.InitializeApplication: Boolean;
begin
  // when core close, this event will be set to notify all of
  // the waiting threads to terminate
  FApplicationCloseEvent := CreateEvent(nil, True, False, nil);


  ......


  // this thread refers to nothing
  FTaskThreadExitEvent := CreateEvent(nil, True, False, nil);
  FTaskThread := TTaskThread.Create(FApplicationCloseEvent, FTaskThreadExitEvent);
end;


procedure TCoreShell.ExitApplication;
var
  dwLoop: Int64;
begin
  if FCoreCloseEvent <> 0 then
  begin
    Windows.SetEvent(FCoreCloseEvent);
  end;


  ......


  // destroy task thread
  if FTaskThreadExitEvent <> 0 then
  begin
    dwLoop := 100;
    while dwLoop > 0 do
    begin
      if WaitForSingleObject(FTaskThreadExitEvent, 0) = WAIT_OBJECT_0 then
      begin
        Break;
      end else begin
        Dec(dwLoop);
        Sleep(100);
        Application.ProcessMessages;
      end;
    end;
  end;


  if FTaskThread <> nil then
  begin
    FTaskThread.Free;
    FTaskThread := nil;
  end;
end;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值