Question

I have a TThread Instance and I would like to wait for a user input. The Thread loads something, waits for the user to click a button and then continues it's task.

I was thinking about setting a global bool to true, yet this wouldn't work too well with instances I think and the thread would have to check the var state in a loop and it seems a little unprofessional.

Is there a safe method for the tthread class to wait for a user input?

Was it helpful?

Solution

You can use a TEvent from the SyncObjs unit.

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


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

The thread does its work, then waits for the event to be signalled by the button click event. By using a TEvent you can also specify a timeout. (or 0 to wait indefinitely).

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;

OTHER TIPS

I used Delphi long ago, so unfortunately I can't provide very specific solution, but I can point you to right direction. You basically need signalling event (TEvent in Delphi's terminology). You can find more info and example here: http://docwiki.embarcadero.com/RADStudio/XE2/en/Waiting_for_a_Task_to_Be_Completed

So essentially event is an object on what you can wait and signal. So the signal waiting for input should wait on event, and on button pressed method you signal event, and thread will unfreeze.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top