强制线程在Windows关闭之前执行

时间:2018-03-16 01:44:08

标签: multithreading delphi delphi-7

我有一个用 Delphi 7 创建的小型Windows软件,其中一个线程会定期执行某些操作,例如在SQLite数据库中保存信息。它工作得很好,但是当Windows即将关闭/重新启动/注销时,同一个线程永远不会执行。这是一个简单的例子:

type
  TSaveText = class(TThread)
  private
    FText: string;
  protected
    procedure Execute; override;
  end;

...

  private
    procedure WMQueryEndSession(var AMsg: TMessage); message WM_QUERYENDSESSION;
    procedure SaveText(const AText: string);

...

procedure AddToLog(const Str: string);
var
  Pth: string;
  Txt: TextFile;
begin
  Pth := ExtractFilePath(ParamStr(0)) + 'log.txt';
  try
    AssignFile(Txt, Pth);
    if not FileExists(Pth) then
      ReWrite(Txt);
    Append(Txt);
    WriteLn(Txt, Trim(Str));
  finally
    CloseFile(Txt);
  end;
end;

procedure TfrmMain.SaveText(const AText: String);
begin
  with TSaveText.Create(True) do
  begin
    FText := AText;
    FreeOnTerminate := True;
    Priority := tpNormal;
    Resume;
  end;
end;

procedure TSaveText.Execute;
begin
  inherited;
  AddToLog(FText);
end;

procedure TfrmMain.WMQueryEndSession(var AMsg: TMessage);
begin
  inherited;
  SaveText('Windows is about to shutdown/reboot/logoff!');
  AMsg.Result := 1;
end;

在此示例中,文本' Windows即将关闭/重新启动/注销!'永远不会保存在日志文件中。但是如果我从线程中删除了该动作,它就可以工作:

procedure TfrmMain.WMQueryEndSession(var AMsg: TMessage);
begin
  inherited;
  AddToLog('Windows is about to shutdown/reboot/logoff!');
  AMsg.Result := 1;
end;

我想知道当Windows即将关闭/重启/注销时,是否有办法强制线程在这种情况下执行。

谢谢!

0 个答案:

没有答案