[英]How to start/stop a monitoring Delphi thread on demand?
我一直在寻找一种方法来监视Delphi中特定的注册表更改。 在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;
在我的应用程序中,我将需要按需启动和停止该线程,但是上面的代码不允许这样做。 仅设置终止标志将不会。
只要以某种方式告诉线程停止等待,然后释放它并在需要时创建一个新线程就足够了。 我如何更改此代码以实现该目标?
使用带有两个事件的数组的WaitForMultipleObjects()
而不是WaitForSingleObject()
。 将手动重置事件添加到线程类,并将Terminated
设置为True
后发出信号。 检查返回值已发出两个事件的信号,并采取相应措施。
编辑:
一些最小的Delphi 2009代码演示了这个想法。 您必须将SyncObjs
添加到使用的设备列表中,并添加
fTerminateEvent: TEvent;
到线程类的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;
您只需要在问题中添加代码即可。 只需尝试释放线程实例即可完成解除线程阻塞的所有必要操作(如有必要)。
相反,在INFINITE中,应在一段时间后使WaitForSingleObject超时。 这样,循环将继续并检查终止。
procedure TRegMonitorThread.Execute;
begin
InitThread; // method omitted here
while not Terminated do
begin
if WaitForSingleObject(FEvent, 1000) = 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;
理论上可以使用TThread.Suspend和TThread.Resume方法来临时停止线程,但是正如Delphi 2010现在所承认的那样,使用它们并不安全。 请参阅Delphi-2010中不推荐使用的TThread.resume应该在什么地方使用? 和http://msdn.microsoft.com/en-us/library/ms686345%28VS.85%29.aspx
这可以工作,只需进行如下较小的更改,现在就调用Terminate:
TRegMonitorThread = class(TThread)
...
public
procedure Terminate; reintroduce;
...
procedure TRegMonitorThread. Terminate; // add new public procedure
begin
inherited Terminate;
Windows.SetEvent(FEvent);
end;
procedure TRegMonitorThread.Execute;
begin
InitThread;
while not Terminated do
begin
if WaitForSingleObject(FEvent, INFINITE) = WAIT_OBJECT_0 then
begin
if Terminated then // <- add this 2 lines
Exit;
...
end;
end;
end;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.