Search code examples
windowsmultithreadingdelphivcl

TThread Wait for User Input


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?


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;