我一直在寻找一种方法来监视 Delphi 中的特定注册表更改。找一个solution在 about.com 上:
procedure TRegMonitorThread.Execute;
begin
InitThread; // method omitted here
while not Terminated do
begin
if WaitForSingleObject(FEvent, INFINITE) = WAIT_OBJECT_0 then
begin
fChangeData.RootKey := RootKey;
fChangeData.Key := Key;
SendMessage(Wnd, WM_REGCHANGE, RootKey, LongInt(PChar(Key)));
ResetEvent(FEvent);
RegNotifyChangeKeyValue(FReg.CurrentKey, 1, Filter, FEvent, 1);
end;
end;
end;
在我的应用程序中,我需要按需启动和停止该线程,但上面的代码不允许这样做。仅设置终止标志是不行的。
以某种方式告诉线程停止等待,然后释放它并在需要时创建一个新线程就足够了。我怎样才能改变这个代码来实现这个目标?
Use WaitForMultipleObjects()
使用两个事件的数组而不是WaitForSingleObject()
。向线程类添加手动重置事件,并在设置后向其发出信号Terminated
to True
。检查返回值,这两个事件中的哪一个已发出信号,并采取相应的行动。
Edit:
一些最小的 Delphi 2009 代码来演示这个想法。你必须添加SyncObjs
到已用单位列表中,并添加
fTerminateEvent: TEvent;
to the private
线程类的部分。
constructor TTestThread.Create;
begin
inherited Create(TRUE);
fTerminateEvent := TEvent.Create(nil, True, False, '');
// ...
Resume;
end;
destructor TTestThread.Destroy;
begin
fTerminateEvent.SetEvent;
Terminate; // not necessary if you don't check Terminated in your code
WaitFor;
fTerminateEvent.Free;
inherited;
end;
procedure TTestThread.Execute;
var
Handles: array[0..1] of THandle;
begin
Handles[0] := ...; // your event handle goes here
Handles[1] := fTerminateEvent.Handle;
while not Terminated do begin
if WaitForMultipleObjects(2, @Handles[0], False, INFINITE) <> WAIT_OBJECT_0 then
break;
// ...
end;
end;
您只需将问题中的代码添加到其中即可。只需尝试释放线程实例即可执行解除线程阻塞所需的一切操作(如果需要)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)