我找到以前做测试的一个例子,希望对你有用。
------------------------------
unit uList;
interface
uses
classes,SysUtils, Windows,SyncObjs;
type
TList = class
ShowMsg
rocedure(i:integer;Text:string)of object;
procedure Test(i:integer;ShowText:string);
private
function SaveLog(sFileName, sMsg: string): integer;
public
//secSendList : TRTLCriticalSection ;
lockxy:TCriticalSection;
constructor Create();//构造器
destructor Destroy;override;//销毁器
end;
implementation
{ TList }
constructor TList.Create;
begin
// 初始化临界区
lockxy:=TCriticalSection.Create;
//InitializeCriticalSection(l.secSendList);
end;
destructor TList.Destroy;
begin
//销毁
//DeleteCriticalSection(l.secSendList);
lockxy.Free;
inherited;
end;
procedure TList.Test(i:integer;ShowText: string);
var
strList:Tstrings;
j:integer;
begin
if assigned(ShowMsg) then
ShowMsg(i,ShowText + ' Start>>>>');
//进入临界区
{ //方法一
EnterCriticalSection(secSendList);
}
//方法二
lockxy.Acquire;
self.SaveLog('T',ShowText + ' Start>>>>') ;
try
strList:=TstringList.Create;
for j:=0 to 300000do
begin
strList.Add(inttostr(j));
if (j mod 10000)= 0 then
begin
self.SaveLog('T',ShowText + ' working...'+ inttostr(j)) ;
end;
end;
finally
strList.Destroy;
self.SaveLog('T',ShowText + ' End||||||||||') ;
//离开临界区
//方法一
//LeaveCriticalSection(secSendList);
//方法二
lockxy.Release;
end;
if assigned(ShowMsg) then
ShowMsg(i,ShowText + ' End|||||||||');
end;
function TList.SaveLog(sFileName, sMsg: string): integer;
var
lsFile : string;
lsPath : string;
lslTemp : TStringList;
lfFile:textfile;//文件
begin
lsPath := ExtractFilePath(ParamStr(0))+'log/' ;
if not DirectoryExists(lsPath) then
ForceDirectories(lsPath);
lsFile := formatdatetime('YYYYMMDD',now());
lsFile := lsPath + lsFile + sFileName;
if fileexists(lsFile) then
//如果存在该文件
begin
assignfile(lfFile , lsFile);
append(lfFile);
writeln(lfFile , sMsg);
closefile(lfFile);
end
else
begin
lslTemp := TStringList.Create ;
lslTemp.Add(sMsg);
try
lslTemp.SaveToFile(lsFile);
except
end;
lslTemp.Free ;
end;
Result := 0;
end;
end.