在一些涉及到多线程的程序设计中,线程常常有一些消息要发送到用户界面进行显示。这方面处理的方法很多,有通过消息传递、全局变量、管道等。这里给出了一种通过消息传递和全局变量相结合的处理的方法。并且把代码封装到一个TLog类中,使用方便。在这里和大家分享。
//TLog类说明部分,事实上该类是一个“日志队列” const MAX_LOG_LEN=1024; type TLog=class private FLock:TCriticalSection;//互斥类,用于线程互斥访问 //定义日志项循环队列--由于队列的特性,最多能保存MAX_LOG_LEN-1条日志 FLines:array [0..MAX_LOG_LEN-1] of string; FHead:integer; FTail:integer; //环队列定义结束 FMsgHandle:THandle;//消息接收窗口句柄 FMsgId:integer;//消息ID FMsgParam:integer;//消息参数,可以用来区分不同的日志对象 function GetIsEmpty: boolean; function GetCount: integer; public constructor Create(const MsgHandle:THandle;const MsgId,MsgParam:integer); destructor Destroy;override; procedure Add(const line:string); procedure Gets(lines:TStrings); procedure Clear; property IsEmpty:boolean read GetIsEmpty; property Count:integer read GetCount; end;
//TLog类实现部分
{ TLog }
constructor TLog.Create(const MsgHandle: THandle; const MsgId, MsgParam: integer); begin FHead:=0; FTail:=0; FMsgHandle:=MsgHandle; FMsgId:=MsgId; FMsgParam:=MsgParam; FLock:=TCriticalSection.Create; end;
destructor TLog.Destroy; begin FLock.Free; inherited; end;
procedure TLog.Add(const line: string); begin FLock.Enter; try FLines[FTail]:=Format('[%s] %s',[FormatDateTime('hh:nn:ss',Now),line]); FTail:=(FTail+1) mod MAX_LOG_LEN; if FHead=FTail then FHead:=(FHead+1) mod MAX_LOG_LEN;//如果队列满,则冲掉头部数据 finally FLock.Leave; end; PostMessage(FMsgHandle,FMsgId,FMsgParam,0);//注意此处未使用SendMessage end;
procedure TLog.Gets(lines: TStrings); begin FLock.Enter; try while FTail<>FHead do begin lines.Add(FLines[FHead]); FHead:=(FHead+1) mod MAX_LOG_LEN; end; finally FLock.Leave; end; end;
procedure TLog.Clear; begin FLock.Enter; try FHead:=0; FTail:=0; finally FLock.Leave; end; end;
function TLog.GetCount: integer; begin FLock.Enter; try if FTail>FHead then result:=FTail-FHead else result:=FTail+MAX_LOG_LEN-FHead; finally FLock.Leave; end; end;
function TLog.GetIsEmpty: boolean; begin FLock.Enter; try result:=FHead=FTail;//头尾重合时为空 finally FLock.Leave; end; end;
原代码:LogUtils.pas
TLog的使用示例
1.消息定义和处理
在主窗口定义消息,如下 const CM_MYLOG=WM_USER+101;
type TForm1 = class(TForm) .... procedure DoMyLog(var msg:TMessage);message CM_MYLOG;//消息相应 .... end;
消息处理代码 procedure TForm1.DoMyLog(var msg: TMessage); var lines:TStrings; begin if(msg.WParam=0) then//注意,这里的0与TLog建立时传入的MsgParam对应 begin if not FLog.IsEmpty then begin lines:=TStringList.Create; try FLog.Gets(lines); Memo1.Lines.AddStrings(lines);//假设输出到Memo1中 finally lines.Free; end; end; end; end;
2.TLog对象定义,初始化/释放
在主窗口或全局中定义变量 FLog:TLog;
一般在窗口建立时生成对象 procedure TForm1.FormCreate(Sender: TObject); begin ... FLog:=TLog.Create(Handle,CM_MYLOG,0);//注意,这里的MsgParam=0 ... end;
在窗口销毁时释放对象 procedure TForm1.FormDestroy(Sender: TObject); begin ... FLog.Free;//注意释放前请确认线程中已经不再使用(或者线程已经终止) ... end;
3.在线程中使用TLog
... FLog.Add('具体的日志');//FLog可以在线程创建时,赋值给该线程的一个成员变量

|