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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.