主程序中用comport串口的OnRxChar()事件接收数据,并存到Tstringlist中,线程ReceiveThread是将Tstringlist中的数据取出来进行处理,现在出现的问题是系统开始运行时正常,一段时间后(时间不等)就会出现“List index out of bounds(0)”的错误,我进行try...except..进行捕捉后出现在Tstringlist.add()中,请问一下,Tstringlist.add()有特殊的地方?//主程序中串口接收字符,其中strlist为TStringlist
procedure TFrm_Main.Comm1RxChar(Sender: TObject; Count: Integer);
var str:string;
begin
comm1.ReadStr(Str,Count);
EnterCriticalSection(cs1);
try
strlist.Add(Str);
except
showmessage('添加缓存出错:');
end;
LeaveCriticalSection(cs1);
end;//线程执行代码
procedure ReceiveThread.Execute;
var str:string;
i:integer;
begin
i:=0;
while not terminated do
begin
if Frm_Main.strlist.Count>0 then
begin
try
i:=Frm_Main.strlist.Count;
str:= Frm_Main.strlist.Strings[0];
Frm_Main.strlist.Delete(0);
Frm_Main.RzStatusPane1.Caption := inttostr(i);
except
Frm_Main.RzStatusPane1.Caption := '缓存中的行数为:'+inttostr(i);
end;
Frm_Main.ProcessRecStr(str);
end
else
begin
try
i:=Frm_Main.strlist.Count;
Frm_Main.RzStatusPane1.Caption := inttostr(i);
sleep(500);
except
Frm_Main.RzStatusPane1.Caption := '缓存中的行数为0';
end;
end;
end;
end;现在系统提示的错误是“添加缓存出错”,所以应该是 strlist.Add(Str);出错。
系统中只在这两段代码中有strlist变量 。
请大家帮我分析一下是什么原因,该怎么解决
procedure TFrm_Main.Comm1RxChar(Sender: TObject; Count: Integer);
var str:string;
begin
comm1.ReadStr(Str,Count);
EnterCriticalSection(cs1);
try
strlist.Add(Str);
except
showmessage('添加缓存出错:');
end;
LeaveCriticalSection(cs1);
end;//线程执行代码
procedure ReceiveThread.Execute;
var str:string;
i:integer;
begin
i:=0;
while not terminated do
begin
if Frm_Main.strlist.Count>0 then
begin
try
i:=Frm_Main.strlist.Count;
str:= Frm_Main.strlist.Strings[0];
Frm_Main.strlist.Delete(0);
Frm_Main.RzStatusPane1.Caption := inttostr(i);
except
Frm_Main.RzStatusPane1.Caption := '缓存中的行数为:'+inttostr(i);
end;
Frm_Main.ProcessRecStr(str);
end
else
begin
try
i:=Frm_Main.strlist.Count;
Frm_Main.RzStatusPane1.Caption := inttostr(i);
sleep(500);
except
Frm_Main.RzStatusPane1.Caption := '缓存中的行数为0';
end;
end;
end;
end;现在系统提示的错误是“添加缓存出错”,所以应该是 strlist.Add(Str);出错。
系统中只在这两段代码中有strlist变量 。
请大家帮我分析一下是什么原因,该怎么解决
既然能使用临界区去实现线程同步,这个低级错误应该不会有的。