gpt4 book ai didi

windows - TThread 等待用户输入

转载 作者:可可西里 更新时间:2023-11-01 09:59:31 26 4
gpt4 key购买 nike

我有一个 TThread 实例,我想等待用户输入。线程加载一些东西,等待用户点击一个按钮,然后继续它的任务。

我正在考虑将全局 bool 设置为 true,但我认为这对实例不太适用,并且线程必须在循环中检查 var 状态,这似乎有点不专业。

tthread 类是否有安全的方法来等待用户输入?

最佳答案

您可以使用 SyncObjs 单元中的 TEvent。

TMyThread = class(TThread)
public
SignalEvent : TEvent;
procedure Execute; override;
end;


TMyForm = class(TForm)
procedure Button1Click(Sender : TObject);
public
myThread : TMyThread;
end;

线程完成它的工作,然后等待按钮点击事件发出信号。通过使用 TEvent,您还可以指定超时。 (或 0 无限期等待)。

procedure TMyForm.Button1Click(Sender : TObject);
begin
// Tell the thread that the button was clicked.
myThread.SignalEvent.SetEvent;
end;

procedure TMyThread.Execute;
var
waitResult : TWaitResult;
begin
// do stuff

// Wait for the event to signal that the button was clicked.
waitResult := SignalEvent.WaitFor(aTimeout);

if waitResult = wrSignaled then
begin
// Reset the event so we can use it again
SignalEvent.ResetEvent;
// do some more stuff
end else
// Handle timeout or error.
end;

关于windows - TThread 等待用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20994046/

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