繁体   English   中英

TThread等待用户输入

[英]TThread Wait for User Input

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

我当时正在考虑将全局布尔值设置为true,但这在我认为的实例中效果不佳,线程必须循环检查var状态,这似乎有点不专业。

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

我很早以前就使用过Delphi,因此很遗憾,我无法提供非常具体的解决方案,但我可以为您指明正确的方向。 您基本上需要信令事件(在Delphi的术语中为TEvent )。 您可以在此处找到更多信息和示例: http : //docwiki.embarcadero.com/RADStudio/XE2/zh/Waiting_for_a_Task_to_Be_Completed

因此,本质上,事件是可以等待和发出信号的对象。 因此,等待输入的信号应等待事件,而按下按钮的方法则通知事件,线程将解冻。

您可以使用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM