gpt4 book ai didi

multithreading - 控制TThread的执行流程

转载 作者:行者123 更新时间:2023-12-03 15:52:10 25 4
gpt4 key购买 nike

如何暂停/继续 TThread 我正在寻找一种安全的替代方案来替代已弃用的 TThread.Suspend 以及 TThread.Resume

最佳答案

这是我最终得到的解决方案。挂起/恢复的安全替代方案。

     type
TMyThread = class(TThread)
private
FHandles: array[0..1] of THandle;
protected
procedure Execute; override;
public
constructor Create;
destructor Destroy; override;
procedure Pause;
procedure UnPause;
procedure Stop;
end;

constructor TMyThread.Create;
begin
inherited Create(False);
FHandles[0] := CreateEvent(nil, False, False, nil);
FHandles[1] := CreateEvent(nil, True, True, nil);
FreeOnTerminate := True;
end;

destructor TMyThread.Destroy;
begin
CloseHandle(FHandles[1]);
CloseHandle(FHandles[0]);
inherited Destroy;
end;

procedure TMyThread.Execute;
begin
while not Terminated do
begin
case WaitForMultipleObjects(2, @FHandles[0], False, INFINITE) of
WAIT_FAILED:
RaiseLastOsError;
WAIT_OBJECT_0:
Terminate;
WAIT_OBJECT_0 + 1:
begin

end;
end;
end;

end;

procedure TMyThread.Pause;
begin
ResetEvent(FHandles[1]);
end;

procedure TMyThread.UnPause;
begin
SetEvent(FHandles[1]);
end;

procedure TMyThread.Stop;
begin
SetEvent(FHandles[0]);
end;

关于multithreading - 控制TThread的执行流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25325731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com