我刚刚编写了自己的日志框架(非常轻量级,不需要大型日志框架).它由一个接口ILogger和许多实现该接口的类组成.我有一个问题是TGUILogger,它将TStrings作为日志记录目标,并将日志记录与主线程同步,以便列表框的Items成员可以用作目标.
type ILogger = Interface (IInterface) procedure Log (const LogString : String; LogLevel : TLogLevel); procedure SetLoggingLevel (LogLevel : TLogLevel); end; type TGUILogger = class (TInterfacedObject, ILogger) public constructor Create (Target : TStrings); procedure Log (const LogString : String; LogLevel : TLogLevel); procedure SetLoggingLevel (LogLevel : TLogLevel); private procedure PerformLogging; end; procedure TGUILogger.Log (const LogString : String; LogLevel : TLogLevel); begin TMonitor.Enter (Self); try FLogString := GetDateTimeString + ' ' + LogString; TThread.Synchronize (TThread.CurrentThread, PerformLogging); finally TMonitor.Exit (Self); end; end; procedure TGUILogger.PerformLogging; begin FTarget.Add (FLogString); end;
日志记录有效,但应用程序未正确关闭.它似乎挂在Classes单元中.堆栈跟踪:
System.Halt0,System.FinalizeUnits,Classes.Finalization,Classes.FreeExternalThreads,System.TObject.Free,Classes.TThread.Destroy,Classes.TThread.RemoveQueuedEvents
我在这做错了什么?
编辑:我刚刚在Delphi帮助TThread.StaticSynchronize中找到以下提示
Warning: Do not call StaticSynchronize from within the main thread. This can cause an infinite loop.
这可能是我的问题,因为一些日志记录请求来自主线程.我怎么解决这个问题?
如果将CurrentThreadID与MainThreadID进行比较,则可以选择是否同步.
就个人而言,我选择让GUI向日志系统询问最新信息,而不是让线程暂停.否则,您的日志记录会干扰线程的快速操作,从而无法实现此操作.