各位好,
我想请问一下关于多个线程的同时只调用同一个组件的问题
我建了四个线程,也同时执行一起执行四个线程.但是他们都对同一个listview操作,发现有一些条码会出现错乱的迹象
例如: 名称 年龄 性别
刘 13 男
刘 13 男
刘 13 男
刘 13 男
男 13 到这一条的时候就会出错了
刘 13 男 我想先说明一下,我的单独调试是完全正确的,无错误.
我想出现这样的错误完全是因为所有的线程都同时写入造成的原故..不知有没有朋友能帮我解答一下这个问题
如果对他实现无错误的输入(不针对ado)
我想请问一下关于多个线程的同时只调用同一个组件的问题
我建了四个线程,也同时执行一起执行四个线程.但是他们都对同一个listview操作,发现有一些条码会出现错乱的迹象
例如: 名称 年龄 性别
刘 13 男
刘 13 男
刘 13 男
刘 13 男
男 13 到这一条的时候就会出错了
刘 13 男 我想先说明一下,我的单独调试是完全正确的,无错误.
我想出现这样的错误完全是因为所有的线程都同时写入造成的原故..不知有没有朋友能帮我解答一下这个问题
如果对他实现无错误的输入(不针对ado)
urlpmi:=strtoint(geturlpm(urlpmp));
if urlpmi>strtoint(xxxx.edit1.Text) then
begin
liststr:=abcxdindex.listview1.Items.Add;
liststr.Caption:=gzz;
liststr.SubItems.Add(inttostr(urlpmi));
liststr.SubItems.Add(aindex.edit1.Text);
liststr.SubItems.Add(DateToStr(Date)+' '+TimeToStr(Time));
inserta(gzz,inttostr(urlpmi),abcxdindex.edit1.text,'abc'); //写进数据库
abcxdindex.statusbar1.Panels[1].Text:='共有记录:'+ inttostr(abcxdindex.listview1.Items.Count); end
我是这样操作的。请问怎么样才能让他不出现错误呢?
能写点代码出来看看吗
procedure OperationListviewEvent;
begin
//Your Code
end;procedure TThread.Execute;
begin
try
Synchronize(OperationListviewEvent);
except
end;
end;
Synchronize(过程A),
具体可参考 <Delphi 5 开发人员指南> 这本书,网上有电子书下的.
procedure OperationListviewEvent;
begin
//Your Code
end; procedure TThread.Execute;
begin
try
Synchronize(OperationListviewEvent);
except
end;
end;
这个方法不能带参数。而我的却有很多参数要加在listview里面.所以该怎么办呀
这个方法的确不能带参数,最简单的你可以在线程的Private里声明几个变量存放这些参数,变相的解决这个参数问题.
// Synchronize内的过程不能带参数,如果需要传递参数可以在线程内设置私有成员
TTest = class(TThread)
private
FPara1:WideString;
procedure OperationListviewEvent;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean);
destructor Destroy; override;
published
property Para1:WideString read FPara1 Write FPara1;
end;
implementationprocedure TTest.OperationListviewEvent;
begin
Listview.add(FPara1);
end;procedure TTest.Execute;
begin
Synchronize(OperationListviewEvent);
end;方法2:uses
SyncObjs;
//声明线程类,在此省略
var
MyTestproc:TCriticalSection;
implementationprocedure TTest.Execute;
begin
//当然,如果用到COM需要初始化COM环境
MyTestproc.Acquire;
try
OperationListviewEvent(Para1,Para2:Widestring);
finally
MyTestproc.Release;
end;
end; initialization
MyTestproc:= TCriticalSection.Create;finalization
MyTestproc.Free;
end.
主线程根据收到的参数填写到LISTVIEW中.