如何处理在Delphi中以线程方式登录

Edu*_*ias 2 delphi thread-safety

德尔福XE2

我有一个带有TMemo的表单,我想展示应用程序启动的几个服务中发生了什么.

我运行的是什么:

  • 使用idContext运行的idHTTPServer响应请求
  • 线程从Dropbox下载更新
  • idUDPServer响应UDP请求
  • 另一个线程负责一些数据库的东西.
  • 主应用程序线程还需要添加日志

基本上,我需要知道如何创建一种标准的,统一的,线程安全的方式来将日志消息引导到我的TMemo,并让用户了解正在发生的事情.

Rem*_*eau 7

既然你已经在使用Indy,你可以使用Indy TIdSync(同步)或TIdNotify(异步)类来TMemo安全地访问.对于简单的日志记录目的,我会使用TIdNotify,例如:

type
  TLog = class(TIdNotify)
  protected
    FMsg: string;
    procedure DoNotify; override;
  public
    class procedure LogMsg(const AMsg; string);
  end;

procedure TLog.DoNotify;
begin
  Form1.Memo1.Lines.Add(FMsg);
end;

class procedure TLog.LogMsg(const AMsg: string);
begin
  with TLog.Create do
  try
    FMsg := AMsg;
    Notify;
  except
    Free;
    raise;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

然后你可以在任何这样的线程中直接调用它:

TLog.LogMsg('some text message here');
Run Code Online (Sandbox Code Playgroud)