sleep会让程序被挂起,所以自己写个等待函数:
timestart:=GetTickCount();
timestop:=timestart;
While (timestop-timestart) <x do
begin
timestop:=GetTickCount();
end;如果启动一个程序的话,还可以正常使用。但是如果我启动3~4个程序,那么CPU的使用率就会一直保持100%,系统什么都做不了。
有没有什么办法让等待的时候程序不占用资源或者占用很少?
timestart:=GetTickCount();
timestop:=timestart;
While (timestop-timestart) <x do
begin
timestop:=GetTickCount();
end;如果启动一个程序的话,还可以正常使用。但是如果我启动3~4个程序,那么CPU的使用率就会一直保持100%,系统什么都做不了。
有没有什么办法让等待的时候程序不占用资源或者占用很少?
timestop:=GetTickCount();
sleep(1);
end;
timestop:=timestart;
While (timestop-timestart) <x do
begin
timestop:=GetTickCount();
Application.ProcessMessages;
end;
我让人向X点移动,发送移动命令之后,我想每2秒比较一下人坐标是否已经到达X点。而这2秒的空闲时间如果用Sleep,我启动的程序比较多系统就会瘫痪了……
Application.ProcessMessages;这句刚刚写进程序,一会测试测试
Application.ProcessMessages 就差不多了
效果的确好了很多~
但是用timer的等待方法不知道是怎么做的,请楼上的朋友详解……
等待时使用WaitForSingleObject
用这个有时候也是很耗费资源的 我是真实经历过一次 所以我现在是用下面的方法:
Procedure Delay(nValue:integer);
var
t:integer;
tmpMSG:TMsg;
begin
t:=Gettickcount();
repeat
FreeCPU();
until Gettickcount()-t>nValue;
end;
procedure FreeCPU();
var
tmpMSG:TMsg;
begin
GetMessage(tmpMSG,Thandle(nil),0,0);
TranslateMessage(tmpMSG);
DispatchMessage(tmpMSG);
end;这样效果似乎比直接用Application.ProcessMessages稍微好些 你可以试试
//延时函数,msec 为微秒(千分之1秒)
var
FirstTickCount: real;
begin
if msec > 0 then
begin
FirstTickCount := GetTickCount();
FirstTickCount := FirstTickCount + msec;
while FirstTickCount > GetTickCount() do
Application.HandleMessage; //关键在这里
end;
end;
//保证完成你的需要,别忘了多给点分。