关于delphi 中 WaitForSingleObject函数的使用
我在编写一个程序的时候遇到 这样的问题
简述吧
dll B 注入到进程A中 同时 执行A的部分代码(B中三个线程)
为了能够保证程序不出问题 我是调用 B中的按钮事件
procedure Tthread3.Execute;
var
i:Integer;
begin
i:=0;
repeat
i:=i+1;
EnterCriticalSection(MyCs); //进入临界区
try
Form1.Button1.click;
Form1.Button3.click;
finally
LeaveCriticalSection(MyCs); //离开临界区
end;
//Delay(5);
sleep(5);
form1.lbl1.Caption:=IntToStr(i);
until i>100000; //十万次
end;
procedure Tthread4.Execute;
var
ii:Integer;
begin
ii:=0;
repeat
ii:=ii+1;
EnterCriticalSection(MyCs); //进入临界区
try
Form1.Button2.click;
Form1.Button3.click;
form1.lbl2.Caption:=IntToStr(ii);
finally
LeaveCriticalSection(MyCs); //离开临界区
end;
// Delay(5);
sleep(5);
until ii>100000;//十万次
end;
procedure Tthread5.Execute;
var
iii:Integer;
begin
iii:=0;
repeat
iii:=iii+1;
EnterCriticalSection(MyCs); //进入临界区
try
Form1.Button1.click;
Form1.Button2.click;
Form1.Button3.click;
form1.lbl3.Caption:=IntToStr(iii);
finally
LeaveCriticalSection(MyCs); //离开临界区
end;
sleep(5);
until iii>100000;//十万次
end;
procedure TForm1.btn1Click(Sender: TObject);
begin
ceshi1:=Tthread3.Create(False);
end;
procedure TForm1.btn2Click(Sender: TObject);
begin
ceshi2:=Tthread4.Create(False);
end;
procedure TForm1.btn3Click(Sender: TObject);
begin
ceshi3:=Tthread5.Create(False);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
InitializeCriticalSectionAndSpinCount(MyCs,400); //这个函数不错 性能彪升。
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
DeleteCriticalSection(MyCs);
end;
end.
[解决办法]
type
Tthread3 = class(Tthread)
private
FEvent: HWND;
procedure aSleep(ms: Word);
public
constructor Create();
destructor Destroy; override;
end;
constructor Tthread3.Create;
begin
FEvent := CreateEvent(nil,True,True,nil);
inherited Create(False);
end;
destructor Tthread3.Destroy;
begin
if FEvent > 0 then CloseHandle(FEvent);
inherited;
end;
procedure Tthread3.aSleep(ms: Word);
begin
ResetEvent(FEvent);
WaitForSingleObject(FEvent,ms);
end;
procedure Tthread3.Execute;
var
i:Integer;
begin
i:=0;
repeat
i:=i+1;
EnterCriticalSection(MyCs); //进入临界区
try
Form1.Button1.click;
Form1.Button3.click;
finally
LeaveCriticalSection(MyCs); //离开临界区
end;
//Delay(5);
//sleep(5);
aSleep(5);//个人觉得sleep 5 太短了啊,这是导致CPU占用高的主因,最好sleep大点
form1.lbl1.Caption:=IntToStr(i);
until i>100000; //十万次
end;