如何使一个线程的一段代码完整的执行情况!(100分)

Y

yinhes

Unregistered / Unconfirmed
GUEST, unregistred user!
我遍了两个线程,ScanThread 和 TestThread
其中
ScanThread .execute
begin
for i:=0 to 255do
begin
if scanIp(i).Status=normal then

AddListItem(ScanIp(i).timeout,i);
end;
end;

AddListItem(TimeOut:String,Index:Integer);
begin
EnterCritical(cs);
with Form1.IpList.Adddo

begin
SubItem[Index].Caption:=Index;
SubItem[Index].add(Timeout);

end;
LeaveCriticalSection(cs);
end;
其中
TestThread .execute
begin
for i:=0 to 255do
begin
if scanIp(i).Status=normal then

UpDataListItem(ScanIp(i).timeout,i);
end;
end;

UpDataListItem(TimeOut:String,Index:Integer);
begin
EnterCritical(cs);
begin
SubItem[Index].Caption:=Index;
SubItem[Index].add(Timeout);

end;
LeaveCriticalSection(cs);
end;
现在我要加一个函数
ScanStopBtn.OnClick
begin
ScanThread.suspend;
TestThread.resume;

end;

会出现问题:
就是当Onclick事件发生时,ScanThread还未退出临界区既全局变量iplist
的拥有权还归案ScanThread,这样一来 TestThread就不能顺利执行.
 
一般说来子线程不能访问VCL,
故你说的情况我得试一试.
 
在Thread.Execute的代码里面访问vcl的函数前加个synchronize试试,
如:synchronize(addListItem(...));
 
这你可以用两个方法解决。
1:用TCriticalSection.详细间delphi help.里面说的很具体。
好象你已经用了。那就应该没问题了。TCriticalSection会管理退出临界。
2:你"一定要"等到ScanThread.suspend;
我认为是没有必要的。
while ScanThread.suspendeddo
begin
TestThread.resume;
end;

给分吧!!我馋死了。
 
在线程中要存取一个公用数据时,需要使用IPC机制。如:互斥(MUTEX)、事件(Event)
临界区(Critical Section)等等。关于这些问题,你可以看WIN 32的HELP。
另外,AKang 同志说的非常正确,在线程中存取界面上的VCL控件资源,一定要注意
使用 Synchronize 。
 
Important: Methods and properties of objects in VCL can only be used in a
method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure ff.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
 
将cs去掉。
用Synchronize(UpdateCaption);
 
多人接受答案了。
 
顶部