gpt4 book ai didi

delphi - 如何以Threaded方式处理Log

转载 作者:行者123 更新时间:2023-12-03 18:08:20 28 4
gpt4 key购买 nike

我有一个带有 TMemo 的表单,我想显示应用程序启动的几个服务中发生的事情。

我在运行什么:

  • 运行 idContext 的 idHTTPServer 响应请求
  • 从 Dropbox 下载更新的线程
  • idUDPServer 响应 UDP 请求
  • 另一个线程负责一些数据库工作。
  • 主应用线程也需要添加日志

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

最佳答案

既然您已经在使用 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;

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

TLog.LogMsg('some text message here');

更新:在 Delphi 2009 及更高版本中,您可以将匿名过程与 TThread.Synchronize()static 版本一起使用>TThread.Queue(),从而使 Indy 的 TIdSyncTIdNotify 类过时,例如:

type
TLog = class
public
class procedure LogMsg(const AMsg; string);
end;

class procedure TLog.LogMsg(const AMsg: string);
begin
TThread.Queue(nil,
procedure
begin
Form1.Memo1.Lines.Add(AMsg);
end
);
end;

关于delphi - 如何以Threaded方式处理Log,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17506615/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com